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.
Related
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.
I'm trying to learn File I/O concepts in C programming language. I'm using GNU / Linux ( Ubuntu 16.04 LTS ) and my IDE is eclipse 3.8. when I try to write in a file through fprintf() method, it doesn't create any files or if the file is even created, it doesn't write in it. I tried to fix the problem by using fflush() or setbuf(file_pointer, NULL) methods as is suggested here but still no change. I guess I'm writing the address of the file in a wrong way.
Here is the code:
#include <stdio.h>
int main(void){
FILE *file_pointer;
file_pointer=fopen("~/.textsfiless/test.txt","w+");
setbuf(file_pointer,NULL);
fprintf(file_pointer,"Testing...\n");
fclose(file_pointer);
return EXIT_SUCCESS;
}
Can someone explain what's wrong here?
On Linux, the ~ in ~/.textsfiless/test.txt is not expanded by the C library fopen... When you use ~ on the command line, it is expanded by your shell (but not by the program using it, started by the shell doing some execve(2)...) into your home directory; the expansion is called globbing. Read glob(7). You are very unlikely to have a directory named ~.
You should read Advanced Linux Programming
So you should check if fopen failed (it is very likely that it did fail). If you want to get a file in the home directory, you'll better use getenv(3) with "HOME" (or perhaps getpwuid(3) & getuid(2)...). See environ(7)
Perhaps a better code might be:
char*homedir = getenv("HOME");
if (!homedir) { perror("getenv HOME"); exit(EXIT_FAILURE); };
char pathbuf[512]; /// or perhaps PATH_MAX instead of 512
snprintf(pathbuf, sizeof(pathbuf),
"%s/.textsfiless/test.txt", homedir);
FILE *file_pointer = fopen(pathbuf, "r");
if (!file_pointer) { perror(pathbuf); exit(EXIT_FAILURE); };
and so on.
Notice that you should check against failures most C standard library (& POSIX) functions. The perror(3) function is useful to report errors to the user on stderr.
(pedantically, we should even test that snprintf(3) returns a length below sizeof(pathbuf) or use and test against failure asprintf(3) instead; I leave that test as an exercise to the reader)
More generally, read the documentation of every external function that you are using.
Beware of undefined behavior (your code is probably having some, e.g. fprintf to a NULL stream). Compile your code with all warnings & debug info (so gcc -Wall -g) and use the gdb debugger. Read What every C programmer should know about undefined behavior.
BTW, look into strace(1) and try it on your original (faulty) program. You'll learn a lot about the system calls used in it.
Most likely your call to fopen() fails. You don't have any checking in your program to ensure fopen even worked. It may not have, and this could be due to a variety of things, like you spelling the path wrong, wrong file or process permissions, etc.
To see what really happened, you should check fopen's return value:
#include <stdio.h>
int main(void){
FILE *file_pointer;
file_pointer=fopen("~/.textsfiless/test.txt","w+");
if (file_pointer == NULL) {
printf("Opening the file failed.");
return EXIT_FAILURE;
}
setbuf(file_pointer,NULL);
fprintf(file_pointer,"Testing...\n");
fclose(file_pointer);
return EXIT_SUCCESS;
}
Edit: Since your comment, you getting the path wrong is most certainly what happened. If you're executing your program from the current directory, and your file is in a folder called "textfiless" in your current directory and your file is called "test.txt", then you'd call fopen like this:
file_pointer=fopen("/textsfiless/test.txt","w+");
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.
I did a program in C but it does not allow to save on c:\SomeDirectory\afile.txt
I'm using this:
FILE* m_hFile = fopen("c:\\SomeDirectory\\afile.txt", "a+t");
fprintf(m_hFile, "testing");
fclose(m_hFile);
Why that? Is there a defined folder I can save in?
SomeDirectory is previously created.
I'm using Windows 7 OS.
If fopen encounters an error, it sets the errno variable indicating what error occurred. You can test this, or even simpler, use perror to print out an error message that will tell you what went wrong:
FILE* m_hFile = fopen("c:\\SomeDirectory\\afile.txt", "a+t");
if (m_hFile == NULL) {
perror("fopen");
}
It sounds like perhaps "SomeDirectory" doesn't exist. You can create folders with C++ but you'll want to check if one's already there. Just calling the open command doesn't automagically create the folder. :)
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.