#Check if a file already exists
44 messages ยท Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
The question is "why do you want to check for the file's existence" to begin with?
Doesn't tell the reason ๐
Not really. The second argument tells whether or not to create the file.
Hence the question: why do you want to check for the file's existence?
Reworded: what use case are you trying to solve?
I mean the exercise says:
Check if a file exists , if not create it and write to it then print the bytes written to the file?
Typically, you write your code for the general, working case and manage to have an exception or an error when things do not go as planned.
There is a problem with that algorithm...
And it is named "time of check to time of use": between the moment the system tells you the file doesn't exist and the moment you actually create it, the file may very well have been created.
Mh, maybe the exercise just want them to get familiar with file handling? Doesn't have to make much sense
Yes, that's typical of assignments, I would say ๐
There's an approach you could take: fopen the file in read mode, that particular open would fail if the file doesn't exist
Have you searched for documentation on fopen?
jes
i could do it with fopen in read mode
then check for null and in this branch i could open it in write mode?
seems kinda weird
Do you have to use fopen() ?
Because if not, then there's a way for the system to return an error if the file already existed while you wanted to create it. And it involves using open() instead with flags O_EXCL and O_CREAT. Read up man 2 open if that suits you.
jesss ill check it out
This question is being automatically marked as stale.
If your question has been answered, type !solved.
If your question is not answered feel free to bump the post or re-ask.
Take a look at !howto ask for tips on improving your question.
#include <stdlib.h>
int main() {
int result = perform_operation();
if (result != 0) {
exit(EXIT_FAILURE); // Terminate program with a failure status
}
return 0;
}
Why is it showing error in online compiler pls help me
What's the error message?
Seems like you haven't defined perform_operation()
If you copied it from some website it's probably a placeholder
Yse, Sir
I'd assume the function performs some random operation and returns an int, 0 if the operation was successful and some other number if otherwise
If you want to test just the failure status you can simply define perform_operation() to return 1 or some such