c语言:从zifu.txt文件中读取任意长度的字符,要求每3个字符中存放一个星号,输出并存入"jieguo.txt"
时间: 2023-06-25 20:02:10 浏览: 56
以下是实现该功能的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 1000
int main() {
FILE *fp_in, *fp_out;
char str[MAX_SIZE];
int i, j;
fp_in = fopen("zifu.txt", "r");
if (fp_in == NULL) {
printf("Failed to open input file.\n");
exit(1);
}
fp_out = fopen("jieguo.txt", "w");
if (fp_out == NULL) {
printf("Failed to create output file.\n");
exit(1);
}
while (fgets(str, MAX_SIZE, fp_in) != NULL) {
i = 0;
while (str[i] != '\0') {
if (i % 3 == 2) {
fputc('*', fp_out);
}
fputc(str[i], fp_out);
i++;
}
}
fclose(fp_in);
fclose(fp_out);
return 0;
}
```
这里使用了`fgets()`函数从文件中读取字符串(一次读取一行),然后遍历字符串中的每个字符,在每3个字符后插入一个星号,并将结果输出到"jieguo.txt"文件中。
需要注意的是,如果文件打开失败,需要及时退出程序,并给出错误提示。