在C中与fread和fwrite的问题

时间:2011-03-15 07:20:09

标签: c file file-io fwrite fread

以下是我的代码,将一些硬编码的int值(1,2,3,4,5)写入文件,关闭该文件,在读取模式下打开同一文件并读取写入的元素。 从输出中可以看出fwrite是正确的,但是fread没有正确读取。

#include<stdio.h>
int main()
{

    FILE *fptr;
    FILE *optr;
    const char *filepath = "E:\\testinput.txt";

              int buf[5]={1,2,3,4,5};
    int obuf[5];
         int value;
    int *ptr = &value;

     int num_bytes_read;

    int no_of_iterations;


    int i;

    int ret;//return value for fwrite

    int count = 0;

    no_of_iterations = 5;

    //open the file

    fptr = fopen(filepath, "wb");
    if(fptr == NULL){
       printf("error in opening input file");
    }

    /*optr = fopen(outFilepath, "wb");
    if(optr == NULL){
           printf("error in opening output file");
    }*/



    printf("int %d ", sizeof(int));

    for(i=0;i<5;i++){
        printf("writing %d",buf[i]);
    ret = fwrite(buf,sizeof(int),1,fptr);
     if(ret != 1)
     {
         printf("error in fwrite:%d\n", ret);
     }
    }
    //written to input file
    fclose(fptr);
    fptr = fopen(filepath, "rb");
            if(fptr == NULL){
               printf("error in opening input file");
            }

    for(i=0;i<5;i++){

            //reading from input file
           num_bytes_read = fread(ptr,sizeof(int),1,fptr);
           if(num_bytes_read == 1){


           obuf[i] = *ptr;//storing into buf what is read from file
           printf("read successful: %d\n", obuf[i]);
           count++;
           }
           else{
               count = 99;
            break;
           }


         printf("\ncount%d", count);

  }


  fclose(fptr);

  return 0;


}

写入的输入文件,如果手动打开(在任何文本编辑器中),则会看到5个非字母数字字符(重复相同的符号) 这是Eclipse中的输出

int 4 writing 1writing 2writing 3writing 4writing 5read successful: 1

count1read successful: 1

count2read successful: 1

count3read successful: 1

count4read successful: 1

count5

2 个答案:

答案 0 :(得分:1)

问题出在这一行:

ret = fwrite(buf,sizeof(int),1,fptr);

fwrite的所有5次调用都具有相同的缓冲区地址,因此每次编写数组的第一个元素1时。

由于您想逐个编写所有数组元素,请将buf+i作为起始地址传递给fwrite

ret = fwrite(buf+i,sizeof(int),1,fptr);

现在fwrite获取的缓冲区的起始地址是数组的i元素的地址。

答案 1 :(得分:1)

在下面的代码中,你总是使用buf,所以你总是写buf [0]

  for(i=0;i<5;i++){
        printf("writing %d",buf[i]);
    ret = fwrite(buf,sizeof(int),1,fptr);
     if(ret != 1)
     {
         printf("error in fwrite:%d\n", ret);
     }
    }

您可以使用&buf[i]代替。或者既然你想玩指针,你也可以使用你的poiner变量:

//write loop
   ptr = buf;
   for(i=0;i<5;i++){
        printf("writing %d",ptr[0]);
        ret = fwrite(ptr,sizeof(int),1,fptr);
        if(ret != 1)
        {
            printf("error in fwrite:%d\n", ret);
        }
        ptr++;
   }

然后你可以相应地修改你的读取循环