1

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.

1
  • Note: ASCII has only 128 characters. Commented Feb 3, 2019 at 0:06

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Why the system treated 26 as an end-of file marker?
@EsmaeelE it is also the value of the Crtl-Z key press, used to indicate EOF from the keyboard (Windows). That value is by definition, in the same way that 13 or Ctrl-M is carriage return.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.