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.
Related
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
I'm working on a problem that requires me to adjust the name of a file and then create a new file using the adjusted name. I'm storing the adjusted name in an array called nameHolder[]. I'd like to use nameHolder, which contains "file.txt" as the name of the new file. The code I have is the following:
void createNewFile(char nameHolder[])
{
FILE* myNewFile = fopen(nameHolder, "r");
fprintf("****************%s******************", nameHolder);
fclose(myNewFile);
}
I get NULL for myNewFile and I believe this is due to "file.txt" not existing in the directory, but the problem requires that I create an entirely new file that doesn't already exist.
From the man page:
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.
For a file to be read, it should exist, which doesn't in your case. fopen returns NULL on failure, you should check for it.
Unrelated:
The prototype of fprintf is:
int fprintf(FILE *restrict stream, const char *restrict format, ...);
The first argument should be a FILE *, remedy it.
You create a file, truncate it present like this:
FILE *myNewFile = fopen(nameHolder, "w");
Otherwise you want the mode "a" (or "a+").
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.
At the moment my program has no problem reading in a .txt file, but my program needs to read in a text file with a different file extension (.emu is the requirement). When simply changing the same file's extension to .emu, the variable 'file' is NULL and therefore the file isn't opened, can anyone help?
Had a little look around and haven't been able to find a solution so any help is much appreciated
here's the source code:
void handleArgs (const char *filename, int trace, int before, int after) {
FILE *file = fopen(filename, "r");
char *address = malloc(MAX_ADD_LENGTH * sizeof(char));
char *instruction = malloc(MAX_INS_LENGTH * sizeof(char));
long int addressDecoded;
if (file == NULL || file == 0) {
fprintf(stderr, "Error: Could not open file");
}
else {
if (ferror(file) == 0) {
while (fscanf(file, "%s %s", address, instruction) != EOF) {
if (strlen(address) == 8 && strlen(instruction) == 8) {
addressDecoded = strtol(address, NULL, 16);
printf("%ld\n", addressDecoded);
//instruction = decodeInstruction(instruction);
}
else {
fprintf(stderr, "Error: particular line is of wrong length");
}
}
}
}
fclose(file);
}
argument 'filename' when executing is simply '/foopath/test.emu'
There's nothing special to C about the file extension. Reread your code for simple errors like changing the filename in one place, but not the other. If you're passing in the filename, pass the whole name, not just the part to the left of the period.
Files are data, and have names. What comes before the dot in a name, is just as much a part of it as what comes after -- the extensions were created just as hints as to what the file contains, but they are NOT required to be strictly related to the file's contents.
The file may not exist, or your priviledges may not be enough to open it. Or maybe there's some other kind of error. How can you diagnose this?
When you use a system call and it doesn't behave the way you want to, there's a variable called errno in errno.h (#include <errno.h>) that will contain a number representing the status of the last call. There's a huge list of symbolic constants to put names to these values, you can google it up.
For example, if you try to open a file and the returned pointer is useless, you might want to check errno to see if the file existed, or if you're exceding system restrictions for opened files, etc.
Here's how I open a file for writing+ :
if( fopen_s( &f, fileName, "w+" ) !=0 ) {
printf("Open file failed\n");
return;
}
fprintf_s(f, "content");
If the file doesn't exist the open operation fails. What's the right way to fopen if I want to create the file automatically if the file doesn't already exist?
EDIT: If the file does exist, I would like fprintf to overwrite the file, not to append to it.
To overwrite any existing file, use the creat call:
#include <fcntl.h>
#include <stdio.h>
int fd = creat (fileName, 0666); // creates file if not exist, overwrite existing
FILE *f = fdopen (fd, "w"); // optional, if FILE * type desired
Did you try just doing fopen(name, "w")? Also, you should perhaps extend your code to report what error is being signalled, using e.g. perror().
Note
Incidentally, I would avoid (at least most of) MSVC's _s functions despite the warnings. There's very little point in the first place except when:
The original function either writes to a passed-in buffer, but does not have a parameter to specify the size of the buffer (e.g. strcat()), or
The original function was permitted/required to return a pointer to a static buffer (e.g. strerror()), which makes
and these functions are non-portable. In short, most of these functions (including fopon_s()) are gratuitously non-portable -- using them makes your program less portable but gives no benefit. (The incompatible addendum for C can only make things worse -- unless MS implements it, in which case it might only make things more confusing.)