[c] Unable to open a file with fopen()

I've been trying to open a file and output text, but I keep getting errors. So I thought I would start at the very beginning and just try opening the file. This is my code:

#include <stdio.h>
#include <stdlib.h>
#define CORRECT_PARAMETERS 3

int main(void)
{
    FILE *file;
    file = fopen("TestFile1.txt", "r");
    if (file == NULL) {
        printf("Error");
    }
    fclose(file);
}

When I run the file, "Error" gets printed to the console and that's it. The TestFile1.txt is in the same location as my .exe. How do I fix this?

This question is related to c file-io fopen stdio

The answer is


Try using an absolute path for the filename. And if you are using Windows, use getlasterror() to see the actual error message.


Instead of printf("Error");, you should try perror("Error") which may print the actual reason of failure (like Permission Problem, Invalid Argument, etc).


A little error checking goes a long way -- you can always test the value of errno or call perror() or strerror() to get more information about why the fopen() call failed.

Otherwise the suggestions about checking the path are probably correct... most likely you're not in the directory you think you are from the IDE and don't have the permissions you expect.


How are you running the file? Is it from the command line or from an IDE? The directory that your executable is in is not necessarily your working directory.

Try using the full path name in the fopen and see if that fixes it. If so, then the problem is as described.

For example:

file = fopen("c:\\MyDirectory\\TestFile1.txt", "r");
file = fopen("/full/path/to/TestFile1.txt", "r");

Or open up a command window and navigate to the directory where your executable is, then run it manually.

As an aside, you can insert a simple (for Windows or Linux/UNIX/BSD/etc respectively):

system ("cd")
system("pwd")

before the fopen to show which directory you're actually in.


Your executable's working directory is probably set to something other than the directory where it is saved. Check your IDE settings.


In addition to the above, you might be interested in displaying your current directory:

int MAX_PATH_LENGTH = 80;
char* path[MAX_PATH_LENGTH];
getcwd(path, MAX_PATH_LENGTH);
printf("Current Directory = %s", path);

This should work without issue on a gcc/glibc platform. (I'm most familiar with that type of platform). There was a question posted here that talked about getcwd & Visual Studio if you're on a Windows type platform.


Well, now you know there is a problem, the next step is to figure out what exactly the error is, what happens when you compile and run this?:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE *file;
    file = fopen("TestFile1.txt", "r");
    if (file == NULL) {
      perror("Error");
    } else {
      fclose(file);
    }
}

The output folder directory must have been configured to some other directory in IDE. Either you can change that or replace the filename with entire file path.

Hope this helps.


Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to file-io

Python, Pandas : write content of DataFrame into text File Saving response from Requests to file How to while loop until the end of a file in Python without checking for empty line? Getting "java.nio.file.AccessDeniedException" when trying to write to a folder How do I add a resources folder to my Java project in Eclipse Read and write a String from text file Python Pandas: How to read only first n rows of CSV files in? Open files in 'rt' and 'wt' modes How to write to a file without overwriting current contents? Write objects into file with Node.js

Examples related to fopen

PHP - Failed to open stream : No such file or directory Getting an error "fopen': This function or variable may be unsafe." when compling Difference between r+ and w+ in fopen() Create a file if one doesn't exist - C PHP php_network_getaddresses: getaddrinfo failed: No such host is known PHP fopen() Error: failed to open stream: Permission denied Writing a new line to file in PHP (line feed) Unable to open a file with fopen() C fopen vs open fopen deprecated warning

Examples related to stdio

Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error GCC fatal error: stdio.h: No such file or directory How can I get an int from stdio in C? Code for printf function in C stdlib and colored output in C 'printf' vs. 'cout' in C++ Unable to open a file with fopen() Detecting EOF in C Rerouting stdin and stdout from C How can you flush a write using a file descriptor?