I'm working on a project where I need to insert a string into a file.
While working on it I faced an issue where fopen function won't detect the files I've created before and file pointer returns null.
I wrote a simple program to test and still the same issue holds.
FILE *file = fopen("/root/file.txt", "w");
fclose(file);
// the file is created properly
file = fopen("/root/file.txt", "r");
if(file == NULL) printf("Failed");
What's interesting is that when I create a file manually fopen has no trouble reading it.
Here I try to create a file using fopen and the accessing it and every time Failed is printed.
I'm using the latest version of vscode and I'm working on macOS 12.6.
Any ideas why this happens?
RETURN VALUE:
Upon successful completion, fopen() shall return a pointer to the
object controlling the stream. Otherwise, a null pointer shall be
returned, [CX] [Option Start] and errno shall be set to indicate the
error.ยน
As you are on a POSIX-compliant system, use perror or strerror to print out an error message instead of that call to printf.
Check if the file was created successfully after the first call to fopen.
An example use of perror:
#include <errno.h>
errno = 0;
FILE *fp = fopen("/root/file.txt", "w");
if (!fp) {
perror("fopen");
...handle error here...
}
[1] https://pubs.opengroup.org/onlinepubs/9699919799/functions/fopen.html
Related
We recently learned opening files in the uni and the prof didn't tell us this. So I open a text file and do a check whether the file is equal to NULL or not.
What if it is equal to NULL? It means that I have no data in the file?
FILE* file = fopen(filename, "r");
if (file == NULL)
{
return 1;
}
if fopen() returns a NULL, it means that the file opening was not successfully accomplished, also in that case it sets the errno global variable is set to duplicate an error. You can also read 'man fopen' in your terminal for more details.
I'm writing a simple code on Linux that writes into a file. That file will be stored in specific path ( not the same path where the executable is located ).The problem is that when I execute the code , the program is terminating with segmentation fault (core dump)
Here is my code :
#include <stdio.h>
int main ()
{
FILE * pFile;
char buffer[] = { 'x' , 'y' , 'z' };
pFile = fopen ("/home/medwajih/Desktop/bufferfile/buffer.txt", "wb");
fwrite (buffer , sizeof(char), sizeof(buffer), pFile);
fclose (pFile);
return 0;
}
Note that the exe of the program is in "/home/medwajih/Desktop/" and the location where I want to create the buffer.txt file is "/home/medwajih/Desktop/bufferfile/"
Thank you.
If the fopen fails (such as if the /home/medwajih/Desktop/bufferfile directory does not exist, or the file exists but has permissions that disallow you replacing it), then pFile will be set to NULL.
Attempting to use it is then undefined behaviour.
You should generally check all calls that may fail to ensure they don't cause issues later on, such as with:
pFile = fopen ("/home/medwajih/Desktop/bufferfile/buffer.txt", "wb");
if (pFile == NULL) {
fprintf (stderr, "Could not create file\n");
return 1;
}
If the problem is actually that the directory does not exist, you can call mkdir beforehand. And, of course, check the return value of that as well :-)
If it's something else (there's not really enough information in the question to ascertain what it is), you need to find a different way to rectify the problem.
I am opening multiple files in a while loop using fopen in C and want to be able to check if any of them will return an error. Relevant code:
int i;
for(i=0; i<10; i++) {
file=fopen(myList[i], "r");
}
How will I know if the file I'm currently looking at will have an error when I attempt to open it or while I am reading it?
From man fopen:
Return Value
Upon successful completion fopen(), fdopen() and freopen() return a FILE pointer. Otherwise, NULL is returned and errno is set to indicate the error.
You can read more about errno in this three questions
While debugging some code I got something like below:
#include<stdio.h>
int main()
{
FILE *fb = fopen("/home/jeegar/","r");
if(NULL == fb)
printf("it is null");
else
printf("working");
}
Here in fopen I gave a somewhat valid path name but not a filename. Shouldn't fopen return NULL then? But it does not return null!
Edit:
If I give path of valid directory in fopen then it will print working:
If I give path of invalid directory in fopen then it will print it is null
Edit:
spec says
Upon successful completion, fopen() shall return a pointer to the object
controlling the stream. Otherwise, a null pointer shall be returned.
so here whether error code set or not, it MUST return NULL
And error code setting is an extansion to ISO C standard standard.
ERROR IS ALSO NOT GOING TO SET HERE
#include<stdio.h>
#include <errno.h>
int main()
{
errno = 0;
FILE *fb = fopen("/home/jeegar/","r");
if(fb==NULL)
printf("its null");
else
printf("working");
printf("Error %d \n", errno);
}
OUTPUT IS
workingError 0
I think that in Unix everything (directories included) is considered to be file so fopen should work on them.
The posix man page man 3p fopen says, in the section ERRORS:
The fopen() function shall fail if:
[...]
EISDIR The named file is a directory and mode requires write access.
(Emphasis mine). Since you are not requesting write access, and chances are that the path you use is a directory, the function does not fail.
About what can you use with a FILE* that refers to a directory, I have no idea.
As you might be very well aware that pretty much everything on Linux system is a file, if not a file then its a process (corrections & remarks welcome :) ) Directory is treated like a file which lists other files (Reference from TLDP); so opening to read a directory as a file is a valid operation and thus you do not get any error. Although trying to write to it is not allowed, so if you open directory in write or append mode, the fopen operation will fail (this has been very well mentioned is other responses & link to fopen documentation). Most of the file operation like read & write operations on this file stream will fail with the error stating that its a directory. Only use which could be found was finding the size of the file (directory in this case) using fseek to SEEK_END & ftell (which will most likely give a result of 4096).
Regarding using errno to get meaningful messages, you can use perror which is in stdio.h & pass message which will be added before the error message or strerror which is in string.h & pass errno which is in errno.h
Hope this helps!
How to check that errno?
You can check errno for example:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
errno = 0;
fp = fopen("file.txt", "r");
if ( errno != 0 )
{
// Here you can check your error types:
perror("Error %d \n", errno);
exit(1);
}
}
Error types you can find at http://pubs.opengroup.org/onlinepubs/009695399/functions/fopen.html Error section.
I am wondering, how to check if I am opening file which exists with fopen? I want to diplay some message, when user selects file with bad name. Is must be some simple checking, but I am not able to solve it.
Thanks
in your param list:
FILE pFile ;
then:
pFile = fopen ("myfile.txt","r");
if (pFile == NULL)
printf("No Such File !! ");
When fopen fails, it returns NULL and sets errno to indicate the type of error.
Check the return value, and if it's NULL check errno. You can use functions like perror or strerror to display simple messages about those errors.
To make it even clearer:
f = fopen("some-file-name.ext", "r");
if (f == NULL) reporterror();
But, probably you don't want to use fopen for checking existence and access right. You should look at stat and access. Both available in C libraries and using man
See the possible errors for open:
However, I think you'll have a hard time finding a way to determine that a filename was invalid. On most systems (except Windows) any string that's not overly long is potentially valid (modulo / being interpreted as a path separator).
fopen() function opens the file whose name is specified in the parameter filename and associates it with a stream that can be identified in future operations by the FILE pointer returned.
FILE *try_to_open = fopen("Document.txt", "r"); //READ ONLY
If the file is successfully opened, function returns a pointer to a FILE object that can be used to identify the stream on future operations; otherwise, a null pointer is returned. So, if you want to check that file has been opened correctly, just check that pointer is not null, in this way:
if (try_to_open == NULL){
puts("Opening file failed.");
} else {
puts("File opened successfully.");
It's simple: the returned FILE* pointer will be null if file doesn't exists.
Of course this assumes you are opening it in r, read mode.