2013-01-06 27 views
5

Im new to C và gặp sự cố khi sử dụng chdir(). Tôi sử dụng một chức năng để có được đầu vào người dùng sau đó tôi tạo một thư mục từ này và cố gắng để chdir() vào thư mục đó và tạo thêm hai tập tin. Khi tôi cố truy cập thư mục qua công cụ tìm (thủ công), tôi không có quyền. Dù sao ở đây là mã của tôi cho điều đó, bất kỳ lời khuyên?Thay đổi thư mục làm việc trong C?

int newdata(void){ 
    //Declaring File Pointers 
    FILE*passwordFile; 
    FILE*usernameFile; 

    //Variables for 
    char accountType[MAX_LENGTH]; 
    char username[MAX_LENGTH]; 
    char password[MAX_LENGTH]; 

    //Getting data 
    printf("\nAccount Type: "); 
    scanf("%s", accountType); 
    printf("\nUsername: "); 
    scanf("%s", username); 
    printf("\nPassword: "); 
    scanf("%s", password); 

    //Writing data to files and corresponding directories 
    umask(0022); 
    mkdir(accountType); //Makes directory for account 
    printf("%d\n", *accountType); 
    int chdir(char *accountType); 
    if (chdir == 0){ 
     printf("Directory changed successfully.\n"); 
    }else{ 
     printf("Could not change directory.\n"); 
    } 

    //Writing password to file 
    passwordFile = fopen("password.txt", "w+"); 
    fputs(password, passwordFile); 
    printf("Password Saved \n"); 
    fclose(passwordFile); 

    //Writing username to file 
    usernameFile = fopen("username.txt", "w+"); 
    fputs(password, usernameFile); 
    printf("Password Saved \n"); 
    fclose(usernameFile); 

    return 0; 


} 
+1

Dòng này khá lạ: 'int chdir (char * accountType); ' – lbonn

Trả lời

5

Bạn không thực sự thay đổi thư mục, bạn chỉ cần khai báo một nguyên mẫu hàm cho chdir. Sau đó, bạn tiếp tục so sánh con trỏ hàm đó với số không (giống như NULL), đó là lý do tại sao nó không thành công.

Bạn nên bao gồm các tập tin tiêu đề <unistd.h> cho nguyên mẫu, và sau đó thực sự gọi chức năng:

if (chdir(accountType) == -1) 
{ 
    printf("Failed to change directory: %s\n", strerror(errno)); 
    return; /* No use continuing */ 
} 
+0

Vì vậy, nếu bạn không nhớ tôi hỏi làm thế nào tôi sẽ thay đổi vào thư mục accountType và tạo hai tệp theo mã? Xin lỗi Im mới đến C. =/và cảm ơn câu trả lời. –

3
int chdir(char *accountType); 

không gọi hàm, hãy thử đoạn mã sau thay vì:

mkdir(accountType); //Makes directory for account 
printf("%d\n", *accountType); 
if (chdir(accountType) == 0) { 
    printf("Directory changed successfully.\n"); 
}else{ 
    printf("Could not change directory.\n"); 
} 

cũng vậy, dòng printf có vẻ đáng ngờ, tôi nghĩ bạn muốn in chuỗi accountType:

printf("%s\n", accountType); 
Các vấn đề liên quan