0

I am trying to open a textfile and reading it char by char. Here is my code:

printf( "Opening the file test.txt in read mode" ) ;
fp = fopen ( "test.txt", "r" ) ; // opening an existing file
if ( fp == NULL )
{
  printf ( "Could not open file test.txt" ) ;
  return 1;
}
printf( "Reading the file test.txt" ) ;
while ( 1 )
{
  c = fgetc ( fp ) ; // reading the file
  if ( c == EOF )
    break ;
  printf ( "%c", c ) ;
}
printf("Closing the file test.txt") ;
fclose ( fp ) ; // Closing the file

The file test.txt exists in the same directory as the program (exe).

When I execute it, fopen() is always returning NULL. Can someone help me, what there could be wrong? Thank you.

BennoDual
  • 5,865
  • 15
  • 67
  • 153
  • 3
    What is your environment? How do you build the program? How do you run the program? From which directory do you *run* the program? Do you know about the concept of [*working directory*](https://en.wikipedia.org/wiki/Working_directory)? – Some programmer dude Dec 29 '20 at 16:08
  • 2
    There are so many things that could be wrong. You might've misspelled the name, the cwd might not be set properly, you might not have read permissions, etc. Your code isn't even runnable, due to a lack of definition for `fp`, and `c`, etc. Please [edit] more details into your question. – Aplet123 Dec 29 '20 at 16:08
  • In which operating system? What environment? Is the file located where the executable file is or where your code is written? – Eden Moshe Dec 29 '20 at 16:11
  • 1
    try an absolute path first – phuclv Dec 29 '20 at 16:25
  • 2
    Let the system tell you why `fopen` failed: `const char *path = "test.txt"; if( (fp = fopen(path, "r")) == NULL ){ perror(path); ...` – William Pursell Dec 29 '20 at 16:50
  • Like @WilliamPursell suggests, use the content of `errno` to find out what is wrong. You did read the documentation of open()`, didn't you? Additionally, check the working directory, depending on your development environment it can be another than the directory of the executable. – the busybee Dec 29 '20 at 17:00
  • Rather than `while(1)`, the more common idiom is `while( (c = fgetc(fp)) != EOF ){ ...` – William Pursell Dec 29 '20 at 17:28
  • 1
    As an addendum to the comment by @WilliamPursell about the loop, remember that `fgetc` returns an **`int`**. This is rather crucial for the comparison to `EOF` to work properly, so you need `c` to be of type `int`. – Some programmer dude Dec 30 '20 at 09:37

0 Answers0