-1

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?

4

1 回答 1

1

我不确定这是否是唯一的问题,但您设置的choice_f 和choice_m 不正确,应该是

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

反而。即您应该改用%c格式说明符。如果您使用%s,将写入一个 nul 终止符(至少);您尚未为此提供存储空间,因此其他堆栈变量将被覆盖。

之后,正如 Nicholas Wilson 所建议的那样,您应该更改flagsint而不是char*(并从作业中删除引号到 O_RDONLY 等)

于 2012-12-03T15:47:43.797 回答