question with fread and fwrite in C
the following is my code to write some hardcoded int values(1,2,3,4,5) into a file, close that file, open the same file in read mode and read the elements written. The fwrite happens properly as seen from the output but the fread does not read correctly.
#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("\nco开发者_开发问答unt%d", count);
}
fclose(fptr);
return 0;
}
The input file written, if opened manually(in any text editor) 5 non-alphanumeric character(same symbol is repeated) is seen Here is the output in Eclipse
int 4 writing 1writing 2writing 3writing 4writing 5read successful: 1
count1read successful: 1
count2read successful: 1
count3read successful: 1
count4read successful: 1
count5
The problem is in this line:
ret = fwrite(buf,sizeof(int),1,fptr);
All the 5 calls to fwrite
have the same buffer address so every time you are writing the first element of the array which is 1
.
Since you want to write all the array elements one by one, pass buf+i
as the starting address to fwrite
:
ret = fwrite(buf+i,sizeof(int),1,fptr);
Now the starting address of the buffer that fwrite
gets is the address of the i
th element of the array.
In the following piece of code, you always use buf, so you always write 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);
}
}
You could use &buf[i]
instead. Or since you want to play with pointers, you could also use your poiner variable :
//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++;
}
And then you can modify your read loop accordingly
精彩评论