0

I'm trying to open and read from a txt file and it should display the content in it but it display just 1 character as a output which is 'ÿ'.

Here is the source code:

int main(){

    FILE *p;

    p=fopen("D:\\eclipse_workspace_cpp\\PL_ODEV2\\inputbookdb.txt","r");
    char c;

    do{
        c = fgetc(p);
        printf("%c",c);
    } 
    while(c != EOF);

    fclose(p);
    return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 2
    Test the return value of `fopen()`, and do not print the character when you get `EOF`. – Edgar Bonet Mar 04 '15 at 15:43
  • `char c;` --> `int c;` Also: check for EOF **before** printing the character. – wildplasser Mar 04 '15 at 15:46
  • `fgetc()` returns a `int`, not a `char`; it can return any `char` value plus the separate value `EOF`. And `EOF` often prints as ÿ (y-umlaut, or U+00FF LATIN SMALL LETTER Y WITH DIAERESIS). If your plain `char` type is an unsigned type, your loop may never end. If your plan `char` type is a signed type, your loop may end prematurely. Neither is correct. Use `int c;`, and test the value before using it (so use `int c; while ((c = getc(p)) != EOF) { … }` instead of a `do … while` loop). – Jonathan Leffler Mar 04 '15 at 15:48
  • "ÿ" corresponds to the code point 0xFF which is mostly EOF... Does the file have any data? – Swanand Mar 04 '15 at 15:49

1 Answers1

1

You can read a file char by char like this:

int main(void) {
   FILE *p;

   // Open file
   if ((p = fopen("D:\\eclipse_workspace_cpp\\PL_ODEV2\\inputbookdb.txt","r")) == NULL) {
       // Couldn't open file
       return EXIT_FAILURE;
   }

   // Step through the file until EOF occurs
   int c;
   while ((c = fgetc(p)) != EOF) {
       printf("%c", c);
       // You might use putchar(c); instead, take a look at the comment below
   }

   // Close file
   fclose(file);

   return EXIT_SUCCESS;
}
pzaenger
  • 11,381
  • 3
  • 45
  • 46
  • It is more symmetric to use `putchar()` or `putc(c, stdout)` rather than the blunderbuss `printf("%c", c)`. There's no real need to use `fgetc()` instead of just `getc()` — but that was in the original code too. – Jonathan Leffler Mar 04 '15 at 15:56
  • Nothing appears in console, I want to print the context, how can I do that ? –  Mar 04 '15 at 17:31
  • @bcng Are you sure, the file is opened correctly? Any error or anything else? What does your file contain? – pzaenger Mar 04 '15 at 17:59