fwrite目标文件为空C语言后

时间:2018-11-12 06:14:03

标签: 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

2 个答案:

答案 0 :(得分:1)

  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);
  }
  ...

答案 1 :(得分:0)

您必须首先检查打开的文件是否未返回NULL,然后只有您可以写入该文件。如此处所示,数据大小是固定的,使用二进制写入模式将整个数组写入文件:

fp = fopen("data2.txt", "wb");
if(fp == NULL)
   {
      printf("Error!");   
      exit(1);             
   }    
fwrite(arr, sizeof(char), sizeof(arr), fp);
fclose(fp);