Basically, I want my code to open a file using a random filename. I expected the code to open the file properly yet, it returns a bad file descriptor even though I'm using a string name.
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main() {
FILE* newFile;
char* newFilename = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[random () % 26];
printf("The file is: %i\n", newFilename);
//Access file
int n = open(newFilename, O_CREAT|O_WRONLY|O_TRUNC, 0777);
newFile = fdopen(n, "wb");
if(newFile == NULL) {
printf("Error: %s\n", strerror(errno));
return 1;
}
free(newFile);
}
CodePudding user response:
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"[random () % 26] is an integer (character code), not a pointer, so it doesn't suit for initializing char*.
You should create a separate buffer to store the character as a part of string.
In other words, you should use:
char newFilenameChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[random () % 26];
char newFilename[] = {newFilenameChar, '\0'};
printf("The file is: %i\n", newFilenameChar);
instead of:
char* newFilename = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[random () % 26];
printf("The file is: %i\n", newFilename);
Also note that passing something not allocated via malloc() family nor NULL to free() is bad. You should use fclose() to close files.
CodePudding user response:
Why is newFilename a char *? Indexing a string returns a char. If you want a random string, you'll need to allocate a string, iterate for how many characters you want, and set characters of that string to random values.
For example:
/* We don't need a null terminator here. */
char alphabet[26] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char *str = calloc(CHAR_COUNT 1, sizeof(char));
int i;
for (i = 0; i < CHAR_COUNT; i ) {
str[i] = alphabet[random() % 26];
}
Also note - not sure why you're opening a file with fdopen instead of fopen and closing it with free instead of fclose.
