Question

I want to create a file with name that input by user.

Here is my code:

int function1(){

    char path[50];
    char choice_f;
    char choice_m;
    int flag;     <-- updated
    mode_t mode;

    printf("Filename : ");
    scanf("%s", path);
    //printf("%s", path);     <-- path can be shown
    printf("\n");

    printf("Desire flag : ");
    scanf("%c", &choice_f);                 <-- updated
    //printf("%s", path);     <-- path CANNOT be shown from here
    while (choice_f != '1' && choice_f != '2' && choice_f != '3'){
        printf("Invalid input! Flag: ");
        scanf("%c", &choice_f);             <-- updated
    }
    if (choice_f == '1')
        flag = O_RDONLY;                      <-- updated
    else if (choice_f == '2')
        flag = O_WRONLY;                      <-- updated
    else if (choice_f == '3')
        flag = O_RDWR;                    <-- updated

    printf("Desire mode : ");
    scanf("%c", &choice_m);                <-- updated
    while(choice_m != '1' && choice_m != '2' && choice_m != '3' && choice_m != '4'){
        printf("Invalid input! Mode: ");
        scanf("%c", &choice_m);                <-- updated
    }
    if (choice_m == '1')
        mode = S_IRWXU;
    else if (choice_m == '2')
        mode = S_IRWXG;
    else if (choice_m == '3')
        mode = S_IRWXO;
    else if (choice_m == '4')
        mode = S_IRWXU | S_IRWXG | S_IRWXO;


    int fd = open(path, (int)flag|O_EXCL|O_CREAT);
    fchmod(fd, mode);
    printf("%d", fd);
    if (fd == -1){
        perror("error");
        return 1;
    }else
        printf("File \'%s\' Created \n", path);
    if (close(fd)<0)
        perror("close()");
    return 0;
}

But at the end of the program, I get the error message:

Error: Bad file descriptor

I tested the path with several times, and seems like after the second scanf(), the path cannot be shown. Even I tried to assign the path to another variable, it's still the same.

What should I do to solve this error?

Était-ce utile?

La solution

I'm not sure if this is the only problem but you're setting of choice_f and choice_m is incorrect and should be

scanf("%c", &choice_f);
scanf("%c", &choice_m);

instead. i.e. You should use the %c format specifier instead. If you use %s, a nul terminator (at the very least) will be written; you haven't provided storage for this so other stack variables will be over-written.

After that, as suggested by Nicholas Wilson, you should change flags to be int rather than char* (and remove the quotes from the assignments to O_RDONLY etc.)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top