我正在尝试打开两个文件,将它们的内容放入数组中并将数组写回到文件中。但是,在我使用 fwrite 函数后,目标文件为空。有人能解释一下如何实现我的目标吗?
data.txt文件内容:
1
2
3
i.txt文件内容:
3
4
5
这是代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
int main(void)
{
FILE *fmain, *fnew, *fp;
int i = 0,f = 0, length = 150, arr[length], chararr[length], sizearr;
char line[130];
int error;
fmain = fopen("data.txt", "rw+");
fnew = fopen("i.txt", "rw");
while(fgets(line, sizeof line, fnew) != NULL){
arr[f] = atoi(line);
f++;
}
fclose(fnew);
// read data into array from data file
while(fgets(line, sizeof line, fmain) != NULL){
arr[f] = atoi(line);
f++;
}
fclose(fmain);
fp = fopen("data2.txt", "w");
fwrite(arr, sizeof(char), sizeof(arr), fp);
fclose(fp);
return 0;
}
当我运行程序后手动打开 data2.txt 时,它是空的,但我希望看到类似的内容:
1
2
3
3
4
5
最佳答案
fopen
没有“rw+”
模式,您可能需要“r+”
模式。- 您需要检查
fopen
是否成功。
试试这个:
...
fmain = fopen("data.txt", "r+");
if (fmain == NULL)
{
printf("Can'topen file.\n"); exit(1);
}
fnew = fopen("i.txt", "r+");
if (fnew == NULL)
{
printf("Can'topen file.\n"); exit(1);
}
...
关于c - fwrite后目标文件为空c语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53256749/