fputc fputs 同时使用
时间: 2024-09-07 20:05:45 浏览: 51
`fputc` 和 `fputs` 都是 C 标准库中的函数,用于向文件流中写入字符或字符串。
- `fputc(int c, FILE *stream)`:这个函数接收一个整型字符 `c` 和一个指向 FILE 类型结构体的指针 `stream`,将 `c` 这个字符追加到指定的文件流中。如果成功,返回字符 `c`,失败则返回 EOF(-1)。
- `fputs(const char *str, FILE *stream)`:它接受一个 const 字符串指针 `str` 和一个 FILE 指针,将字符串 `str` 中的所有内容逐字节追加到文件流中,直到遇到换行符 '\n' 或字符串结束。函数返回的是实际写入的字符数,不包括换行符,如果整个字符串都已写入,则返回 strlen(str),失败时返回 EOF。
两者结合使用时,通常会在 `fputs` 中插入多个字符,例如你想在一次操作中先写入一个字符串,然后写入特定的字符,可以这样做:
```c
char str[] = "Hello, ";
int c = '!';
FILE *fp = fopen("example.txt", "w"); // 打开文件
if (fp != NULL) {
if (fputs(str, fp) == EOF) {
printf("Error writing to file.\n");
}
if (fputc(c, fp) == EOF) {
fclose(fp); // 关闭文件并处理错误
printf("Error writing character.\n");
} else {
fclose(fp); // 文件写入完成,关闭文件
printf("Character written successfully.\n");
}
} else {
printf("Failed to open the file.\n");
}
```
阅读全文
相关推荐

















