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?