DibaHadie
DibaHadie

Reputation: 1

fopen function in c : no such file or directory

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?

Upvotes: 0

Views: 822

Answers (1)

Madagascar
Madagascar

Reputation: 7345

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

  1. As you are on a POSIX-compliant system, use perror or strerror to print out an error message instead of that call to printf.

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

Upvotes: 4

Related Questions