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("\ncount%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