Error opening file - c

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.

Related

Opening and Creating files in C Issue?

So, I have written a simple program in C which opens a file called prog6_input.txt and generates another file called prog_output.txt. However, the code below works perfectly for Windows but fails whenever I compile on a Mac. (I also assume this is having the same issue with create the file as well)
FILE *ptr_file = fopen("prog6_input.txt", "r");
// We Don't have a input file
if(!ptr_file) {
perror("Error Reading Input file.\n");
return 1;
}
For perror:No Such file or directory
The file, as seen in the screenshot below, is in the same directory. This works in windows, but does not in Mac OSX? Why is this and how would i fix it?
UPDATE: In order to vompile i used make main in the directory using terminal.
You should open up a terminal, cd to your Prog6 directory, and run your executable with ./main.

How to make .txt files visible to Visual C

I'm writing a program to that needs to read 32-bit binary numbers in as strings from a text file (notepad). The file contents look like this:
11111111111111110111100011111110
11111111111111111111111111110101
00000000100001011010101011110101
00000000000000000000000010010001
Every time I try to run the code I get the error message saying that the debug assertion failed because the (stream != NULL) condition was not satisfied. I assume that this comes from an error with the fscanf part of the code. I have looked at similar questions with the solution usually being to move the text file to the current working directory, but I am not sure what this means. I am using visual studio Express 2013, and have the text file saved under resource files in my console application. I also have the console application and the text file saved in a single folder on my desktop. Neither of these seem to have had any effect in resolving the error. Here is my source code if it helps at all:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<math.h>
void main()
{
char str[34];
FILE *binnz;
binnz = fopen("binns.txt", "r");
while (fscanf(binnz,"%s",str) != EOF)
{
printf("%s\n", str);
}
fclose(binnz);
}
If the problem is where the text file is stored, where -exactly- do I put it?
Thanks in advance.
I have looked at similar questions with the solution usually being to move the text file to the current working directory, but I am not sure what this means.
The working directory of a program basically allows it to open files by a relative path. Typically, the working directory of a program will be wherever the executable file resides (so it can easily reference files in the same directory); however, when debugging in Visual Studio, it'll use the project directory as the working directory by default. You can change this under the "Debugging" page of your project settings, or you can just put binns.txt in your project directory.
The resource directory is the wrong place. Add a system("dir") to your program, and it will show you where your program is running. Put your file in there, and you should be good to go.

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.

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?
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.

Resources