12

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?

unwind
  • 391,730
  • 64
  • 469
  • 606
jet
  • 173
  • 1
  • 1
  • 6

8 Answers8

22

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

Grofit
  • 17,693
  • 24
  • 96
  • 176
Kousik Nandy
  • 496
  • 2
  • 5
  • 13
    If you find `perror` not flexible enough, you could also use `printf("Error: %d (%s)\n", errno, strerror(errno))` or even `printf("Error: %m\n")` (a Glibc extension). – ephemient Nov 17 '09 at 15:54
16

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • 2
    No need for the backslashes, which often lead to subtle errors by people that have problems getting things like `fopen()` to work. You should recommend forward slashes. –  Nov 17 '09 at 04:12
  • 2
    I neither recommend forward nor backward slashes since the standard doesn't mandate the format of the filename at all. But you're missing the point if you downvoted for that reason - the intent was just to demonstrate the use of a full file path. – paxdiablo Nov 17 '09 at 04:23
  • Could you please have a look at the following: `FILE *pFile = NULL; const char *filename = "E:/CODE/TEST/test.txt"; pFile = fopen(filename, "r");` and tell me what I'm missing or doing wrong. I also tried: `const char *filename = "E:\\CODE\\TEST\\test.txt";`. Nothing seems to work. Program gets executed but prints nothing on `cmd`. It shows the following warning: `Warning 1 warning C4133: 'function' : incompatible types - from 'FILE *' to 'const char *`. IDE: VS 2013. – phougatv Oct 02 '15 at 10:10
  • @barnes, ask a *question,* don't leave a comment. That way, you'll get a lot more exposure. As an educated guess, I'd suggest you're using `filename` somewhere where you should be using `pFile`, or vice versa. – paxdiablo Oct 02 '15 at 11:34
5

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

Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
  • Yep. For instance, [Visual Studio](http://en.wikipedia.org/wiki/Microsoft_Visual_Studio) may set the current directory to where the solution (.sln) file is whereas the EXE file may be down in folder "Debug". – Peter Mortensen May 22 '17 at 20:35
5

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.

Rob Pelletier
  • 327
  • 2
  • 3
5

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);
    }
}
Robert Gamble
  • 106,424
  • 25
  • 145
  • 137
2

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.

Community
  • 1
  • 1
Dan
  • 955
  • 6
  • 11
1

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rplusg
  • 3,418
  • 6
  • 34
  • 49
0

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.

Richie
  • 9,006
  • 5
  • 25
  • 38
  • Great comments. Now I am able to open my file at least manually this way. How would I do it from the command line in Visual Studio? I tried this on XCode by adding parameters, but it just wasn't working out for me. I was hoping that Visual Studio would give me more luck. Thanks! – jet Nov 17 '09 at 04:47
  • XCode and Visual Studio might set different working directories, but the problem is the same, and so is the solution. You need to include code in your application that changes to the directory you want. – wadesworld Nov 17 '09 at 05:34