Reputation: 345
I want to create N files in a for loop under Linux as O.S.; This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *ptr;
char name[25];
for (int i = 0; i < 10; i++) {
snprintf(name, sizeof(name), "File_Nr%d.txt", i);
ptr = fopen(name, "w");
if( ptr == NULL ){
perror("Error creating file!");
}
fclose(ptr);
}
return 0;
}
It works and creates File_Nr0.txt to File_Nr9.txt.
Question: is this code "safe"?
Upvotes: 0
Views: 67
Reputation: 1902
Perhaps since you want to only create the files, you can directly use the open()
system call, which has more options and more readable way of expressing options IMO.
int fd = open(name, O_WRONLY|O_CREAT|O_TRUNC,
S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP | S_IROTH);
or
int fd = creat(name, 0644) // consider it to be an alias for above.
if you want to fail when the file exists already,
int fd = open(name, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL, 0644);
in fopen()
you can achieve this by using the 'x'
in mode
param.
ptr = fopen(name, "wx");
And as @xception mentioned, you should return a non-zero error code when something goes wrong.
if (NULL == ptr) {
perror("...");
return -1; // or better the errno which was set by open() call..
}
And in your code, you attempt to close the ptr
even in failure case, that is gonna give you a crash. So, you need to handle that.
Upvotes: 3