Reputation: 33
I am printing the first 128 ASCII characters in a file and then trying to read those characters printing their ASCII decimal value.
I tried using fread() and fscanf() functions but both stop after reading first 25 characters.
#include <stdio.h>
int main()
{
int i;
char ch;
FILE *fp;
fp=fopen("a.txt","w+");
for(i=0;i<128;i++)
{
fprintf(fp,"%c",i);
}
fseek(fp,0,SEEK_SET);
while(fread(&ch, sizeof(char), 1, fp))
printf("%d\n",ch);
return 0;
}
I expect the output to be the decimal value of the first 128 ASCII characters but the actual output only have decimal value of first 25 ASCII characters.
Upvotes: 1
Views: 2732
Reputation: 34575
When you reached 26
the system treated that value as an end-of file marker. All 128 bytes were written but on reading it stopped at value 0x1A
(26). This behaviour is for a text file (Windows).
I opened the file in binary mode, and it worked.
fp = fopen("a.txt", "wb+");
If t
or b
is not given in mode
, the default translation mode is defined by the global variable _fmode
.
Aside: you should check the return value from fopen
. If it is NULL
the file could not be opened. You should fclose
the file too.
Upvotes: 3