Save file with C fopen - c

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. :)

Related

problem in using fprintf_s(getting warnings) in c

I'm new in c.I just want to complete my project.a list of student with struct.and one of the option is save data in a file.
I using visual studio 2022 and BTW I can't use syntaxs like scanf or something like that.I have to use scanf_s and etc
anyway for fprintf_s I don't know how can I use it for my project.I searched in stackoverflow and another sites about it syntax but they were not usefull, but vs gives me a warning. it is:
sttp could be '0'
the source code is :
FILE* sttp;
fopen_s(&sttp, "text.txt", "w");
fprintf_s(sttp, "test");
fclose(sttp);
and there are some warnings the image of error list
When you try to open a file with fopen_s function, it may or may not succeed, so you must check the return value of that invocation.
If for some reason, the file was not opened, then your file pointer variable, sttp will not be initialized, hence the VS IDE is showing you the warning.
Modify your code, like below.
FILE* sttp;
if(0 == fopen_s(&sttp, "text.txt", "w") )
{
fprintf_s(sttp, "test");
fclose(sttp);
}

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.

C check if file exists

In a project I have to do in C89 standard I have to check if a file exists.
How do I do this?
I thought of using
FILE *file;
if ((file = fopen(fname, "r")) == NULL)
{
printf("file doesn't exists");
}
return 0;
but I think there can be more cases then file doesn't exists that will do fopen == NULL.
How do I do this? I prefer not using includes rather then .
If you can't use stat() in your environment (which is definitely the better approach), just evaluate errno. Don't forget to include errno.h.
FILE *file;
if ((file = fopen(fname, "r")) == NULL) {
if (errno == ENOENT) {
printf("File doesn't exist");
} else {
// Check for other errors too, like EACCES and EISDIR
printf("Some other error occured");
}
} else {
fclose(file);
}
return 0;
Edit: forgot to wrap fclose into a else
It's impossible to check existence for certain in pure ISO standard C.
There's no really good portable way to determine whether a named file
exists; you'll probably have to resort to system-specific methods.
This isn't a portable thing, so I'll give you OS-specific calls.
In Windows you use GetFileAttributes and check for a -1 return (INVALID_HANDLE or something like that).
In Linux, you have fstat to do this.
Most of the time however, I just do the file opening trick to test, or just go ahead and use the file and check for exceptions (C++/C#).
I guess this has more to do with system environment (such as POSIX or BSD) than with which version of C language you're using.
In POSIX there is a stat() syscall that will give you information about a file, even if you cannot read it. However, if the file is in path that you have no access permissions to it's always going to fail regardless of whether the file exists.
If you have no access to the path then it should never be possible to look on files contained.
Do you really want to access the file? A check is usually better with the
access(filename,F_OK)==0 from <unistd.h> and is a pretty wide standard, I think.

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