0

I am trying to read a file character by character and print it on screen. However, the character is not displaying, I am getting a box with 0001 in it. This is my code

#include <stdio.h>
#include <stdlib.h>
int main()
{
    FILE *fp;
    int ch;

    fp=fopen("myfile.txt", "rb");

    while((ch = getc(fp)) !=EOF){
        putc(ch, stdout);
    }

    fclose(fp);

    return 1;
}
Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73
user3531263er
  • 423
  • 1
  • 4
  • 20
  • 3
    working for me. can you show your input file? – Jayesh Bhoi Apr 14 '14 at 09:18
  • If `myfile.txt` is a text file, then do not use "b" in `fopen()` mode. – Lee Duhem Apr 14 '14 at 09:22
  • 1
    Working for me too. Also, I think, that box displays the value returned from `main()`. You should return `1` from `main()` if some error occured. If there are no errors, you should return `0`. – HolyBlackCat Apr 14 '14 at 09:23
  • 1
    Perhaps your file actually contains that character (0x1). You could verify this by replacing `putc(ch, stdout)` with `printf("%02X ", ch);`. Of course you should check `fp != NULL` before doing all this. – M.M Apr 14 '14 at 09:32
  • I had to reinstall my Ubuntu VM. There was an issue with that, this code works now. Thanks – user3531263er Apr 14 '14 at 11:08

2 Answers2

0

you need to check the return values from fopen, to ensure you opened the file successfully, you could be executing from the wrong directory. Plus if your file is a TEXT file, you should be opening using "rt".

Anonymouse
  • 935
  • 9
  • 20
0

Basic File Opening modes in C is

"r"-reading

"w"-writing

"a"-append

"r+"-reading+writing

"w+"-reading+writing

"a+"-"reading+appending"

This code is enough to read .txt files

#include <stdio.h>

#include <stdlib.h>

int main()

{

FILE *fp;

int ch;

fp=fopen("myfile.txt", "r");

while((ch = getc(fp)) !=EOF){



    putc(ch, stdout);


}



fclose(fp);


return 0;

}

Merp
  • 65
  • 11
  • to those modes, you can then add "b" for binary files, or "t" for text. I believe text is the default, but I always like to specify which mode I'm using just to be totally clear. – Anonymouse Apr 14 '14 at 10:15