简体   繁体   中英

Reading ASCII characters from a file in C

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM