Unable to open a file with fopen() - c

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?

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

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.

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.

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);
}
}

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.

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

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.

Related

Is there a reason why C doesn't let me write to this file?

I am new to C, and I am trying to get the hang of file handling. I have tried writing to this file but its not working, and I am not sure why it doesn't work, could someone help me?
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *f;
f = fopen("out.txt","w+");
if (f == NULL) {
printf("ERROR");
exit(-1);
}
char test[] = "HELLO";
fprintf (f, "%s", test);
fclose(f);
return 0;
}
I keep getting the "ERROR" message when I check if the file has been opened :/
Replace rather useless
printf("ERROR");
with
perror("fopen");
C doesn't require fopen to set errno (which is used by perror), but POSIX does, and the usual compilers for Linux and Windows set it.
The error is almost surely going to be EPERM ("Permission denied"). That error means one of the following:
you don't have permission to access that directory,
you don't have permission to write to that directory (if the file doesn't exist),
you don't have permission to read that directory (if the file exists),
you don't have permission to modify the file (if the file exists), or
the file is locked by another program (if the file exists).
Well, other causes are possible, but so unlikely I don't know what they would be.
Your program attempts to create or modify a file in the current directory. Note that the current directory is not necessarily the directory in which the executable is located. You're probably trying to write to the wrong directory accidentally.

Unexpected error when reading from a text file in C

I'm trying to read text from a file (should be pretty easy right?). As far as I recall, the syntax should look something like
FILE *filename;
filename = fopen("filename.txt", "r"); /*when file is the same
folder of the .exe*/
Below is my code. When I run it, I simply get "Error", which is the prompt I wanted in case of an error. I included here a global struct declaration because it's literally the only other thing in the code, even though I'm positive it's not causing any problem with opening the file.
#include <stdio.h>
#include <stdlib.h>
struct list {
char subject[20];
char prof_name[20];
char prof_surname[20];
char period[20];
int credits;
int pass_rate;
};
int main()
{
struct list data[80];
FILE *prof;
prof = fopen("professor.txt", "r");
if (prof == NULL) {
fprintf(stderr, "Error");
exit(EXIT_FAILURE);
}
return 0;
}
The file has the correct name and extension, it's in the same folder as the .exe (I've also tried with the address, it still does the same). I feel like I'm going to get crazy if I look at the code even for just one more minute. There must be something I missed
Regarding the comment "when file is the same folder of the .exe", that is incorrect.
Instead relative paths (like your professor.txt) is relative from the process current working directory. Which might be very different from the location of the .exe file.
My guess is that you're running inside Visual Studio (or other IDE) which places the executable files in a sub-directory. The working directory when running, though, is usually the project root directory.
So either go into the project settings and change the working directory when running the program into the directory where the file is located, or move the file to the actual working directory.
You can use the _getcwd function to get the process working directory, to verify that it is what you believe it is.

Error opening file

RESOLVED. Problem -
The lecturer uploaded a text file called file.txt and this resulted in a file "file.txt.txt"... I am feeling a mix of frustration and stupidity right now.
Original problem
I'm having trouble with C using Visual Studio 2012 on Windows 7 trying to open a text file using fopen. I'm not too sure which directory this file.txt should be in so I tried placing it with the .vcxproj file AND the .exe file which is in the Debug directory created by VS.
With no success, I tried including the full path to the file in the fopen function.
This code compiles fine but when I run it, I get an error saying "No such file or directory"
What am I doing wrong and how can I fix it? I'm really confused here and any help would be most welcome! Thanks in advance.
Code below:
int main(void)
{
FILE *fp;
fp = fopen("C:\\Directory\\file.txt", "r");
if (fp == NULL)
{
perror("Error opening file\n");
}
return 0;
}
Do you really have any file at this place "C:\Directory\file.txt" I guess you do not have one.
I tried the code and it runs perfectly fine for me. Initially I was getting the same error and that was because the file was not there. Once I put the file there, it all worked perfectly as expected.
Please check again that the file is in place.
You should include the proper header for fopen(), which is
#include <stdio.h>
Make sure all the backslashes are really escaped (doubled) in your filename, too.

Reference a file in C static library

I created a static library in C using Visual Studio. This library contains a function which accesses a text file stored in that current directory. The library was built properly. But the problem is that when I call the function from outside other project it is not loading that text file( I linked the .lib file properly everything else is working except for loading of that file).
Any ideas how to load a text file from .lib file just by relative path??
Thanks in advance..
The following is the library test function definition
int test()
{
FILE *fp = fopen("hello.txt", "r");
if(!fp) printf("File Error");
return 0;
}
The test.lib file is built and created for this.
Just accessing the current folder hello.txt file but when this function is called from other Project. it is saying File Error.
Modify your code to look at the errno:
#include <errno.h>
#include <string.h>
...
if(!fp) printf("File error: %s\n", strerror(errno));
And then look up the meaning of the errno on your operating system to see what's going on.
I'm pretty sure the fact that you're calling this function from a library is a red herring.
What's most likely happening is that your hello.txt file is not in the working directory of the executing process. Go ahead and #include <windows.h> in your project, and use the GetCurrentDirectory function to see what the working directory is when you run your program. Most likely, it's not the same path as your text file.
To remedy this, you can do one of two things: you can change the startup settings of the program (whether that's from Visual Studio or a Windows shortcut) to specify the working directory (called "Start in:" for a Windows shortcut) to be the path to the text file you want to open, or you can figure out what working directory your program has been using and move your text file there instead.
Edit: Also, if you want the application to use its own directory (where the executable file actually resides) you can use the GetModuleFileName function to get the full path of the executable. Of course, you'll have to trim the filename of the program off the end of the string it produces, but that should be a piece of cake.
Check your file path and print an errno, I think you have a static file path

Netbeans and C, peculiar bug

I am writing something in C using Netbeans 6.9.1 (its a requirement) and I stumbled upon a peculiar bug. When I try to run this code from Netbeans:
#include <stdio.h>
#include <stdlib.h>
#include "company_description.h"
company_description read_company_description() {
char file_name[FILE_NAME_BUFFER_SIZE];
FILE *company_description_file;
company_description cd;
printf("Please enter the name of the file containing the "
"company's description: \n");
scanf("%50s", file_name);
company_description_file = fopen(file_name, "r");
if(company_description_file != NULL) {
printf("file is not null\n");
}
fscanf(company_description_file, "%s%s%s%s%s%s", cd.company_name,
cd.name_file_deliveries_info, cd.name_file_industrial_park,
cd.name_file_places, cd.name_file_roads, cd.name_file_vans_info);
return cd;
}
I get this output:
Please enter the name of the file containing the company's description:
name_file.txt
Segmentation fault
Press [Enter] to close the terminal ...
Ok I say to myself, from my point of vie there is nothing wrong with this code and I go to
~/path/to/NetbeansProject/dist/Debug/GNU-Linux-x86 and try to run the executable from there and it works. I forgot to mention that the file that should be read is in that same folder, exactly where the executable is. Now there might be a mistake on my side but I don't see it so any thoughts about this would be helpful. Thanks!
As to why it doesn't run in Netbeans: working directory is probably incorrect - when you run from Netbeans, the working directory is not necessarily the same as where the executable resides.
I do not have Netbeans installed, but you can set the working directory (what directory the system thinks the executable was executed in) in your project's settings.
I also agree with aschelper's answer - if you don't get a valid FILE * back you don't want to continue running that file code.
Your code will probably crash if fopen fails. Sure, you have a check for whether company_description_file != NULL, but then if it is null you go ahead and pass it to fscanf anyway (rather than exit()ing or returning early or something). Undefined Behavior.
Don't blame the compiler/IDE, the bug is in your code :)
company_description_file = fopen(file_name, "r");
if(company_description_file != NULL) {
printf("file is not null\n");
}
fscanf(...
There is an else missing that will cope with the situation when the file is not found. Right now you pass a NULL pointer to fscanf which causes the crash. Your program cannot find the file most probably because NetBeans sets the working directory somewhere else. Make sure you set the correct working directory or copy the input file to the proper location.

Resources