c - fwrite后目标文件为空c语言

标签 c fwrite

我正在尝试打开两个文件,将它们的内容放入数组中并将数组写回到文件中。但是,在我使用 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

最佳答案

  1. fopen 没有“rw+” 模式,您可能需要“r+”模式。
  2. 您需要检查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/

相关文章:

arrays - 如何将数组中的变量存储在不同的文件中

C 将 uint16 写入文件出现错误

c - 段错误 w/fwrite

c - scanf 中的额外/缺失字符

c++ - 为什么 float 计算和转换在调试和发布配置中显示不同的结果?

c - 在同一个数组上重复找到最小值

c - 如何在 C 中设置 20 mbs 的数组大小

c - C中的双重比较

c++ - 将用户定义的数据类型保存到 C++ 文件中

c - 如何从串口读取数据并将其写入文件