简体   繁体   中英

C program returns bad file descriptor on creating file with char * as filename

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);
}

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM