0

I am new to C and i am trying to read a .txt file. I am using a windows 10 machine. I have created the file and i am trying to read it. I will share all my code below.

    int main()
{
    char firstline[255]; 
    FILE * fpointer = fopen("klinks.txt", "r");
    fgets(firstline, 255, fpointer); 
    printf("%s", firstline);
    fclose(fpointer); 
    return 0;
}

Below is the message showing on the console terminal. I have no idea why.

h┐
Process returned 0 (0x0)   execution time : 0.026 s
Press any key to continue.
Uche
  • 13
  • 5

2 Answers2

1

It doesn't find the file, and the fgets call doesn't do anything, and the output is just the default garbage in firstline string. When you create the file the program works.

Also add a check for null after the fopen call.

George Nechifor
  • 439
  • 3
  • 12
  • I do not know how to add the check. are you also saying that i should create the file? the file is already created. I am just trying to read the file – Uche Jun 25 '21 at 12:15
  • @Uche: After the line `FILE * fpointer = fopen("klinks.txt", "r");`, add the line `if ( fpointer == NULL ) { fprintf( stderr, "Error opening file!\n" ); return 1; }` Note that you must insert the newlines into the code yourself, because I can't write newlines in comments. – Andreas Wenzel Jun 25 '21 at 12:17
  • 1
    guys i have found the mistake. My bad. You pointed me in the right direction. I was trying to read a file that was in another directory. Immediately i copied the file into the same directory that i was trying to read from, the first line showed. Thanks a lot man for telling me that it could not find the file. – Uche Jun 25 '21 at 12:18
  • Thanks a lot for your help. I have found the issue. Thnaks a lot again – Uche Jun 25 '21 at 12:21
0

You need to check the value of file descriptor which is getting returned by fOpen() function just to make sure system call has not failed.

try using fread : fread reads raw data -- it will stop after a specified (or default) number of bytes, independently of any newline that might or might not be present.

You might want to check this : fgets() and fread() - What is the difference?