2017-04-02 95 views
0

我有一個簡單的代碼,以讀模式從hdd打開一個文件,但文件的路徑已經在代碼中給出了。我希望用戶手動提供文件名,路徑和文件通過控制檯打開類型。我必須爲此做些什麼?C從控制檯打開文件

#include<stdio.h> 

int main() { 
    FILE *fp; 
    fp = fopen("D:\\samplefile.txt","r");  
    if(fp != NULL) { 
     printf("File has been opened");   
     fclose(fp); 
    }  
    else printf("File not found"); 
    return 0; 
} 

回答

0
// Use of function scanf is done here as an simple use. There are other ways also to get input from user 
#include<stdio.h> 
int main() 
{ 
    FILE *fp; 
    char filePath[100]; 
    printf("Enter Path name: "); 
    scanf("%s", filePath); 
    printf("value is %s",filePath); 
    fp = fopen(filePath,"r");  
    if(fp != NULL) { 
     printf("File has been opened");   
     fclose(fp); 
    }  
    else printf("File not found"); 
    return 0; 
} 
+0

但我怎麼輸入文件開放型R,W或?我似乎無法將任何東西放在「..」 – Epiphany13

+0

下面的答案應該解決這個問題。你可以輸入如r或rw的輸入。不要輸入你在輸入中輸入的任何空格 –

0
#include <stdio.h> 

int main() 
{ 
    FILE *fp; 
    char filePath[100],filePermission[10]; 
    printf("Enter Path name: "); 
    scanf("%s", filePath); 
    printf("Enter file permission parameters: "); 
    scanf("%s", filePermission); 

    fp = fopen(filePath,filePermission);  
    if(fp != NULL) { 
     printf("File has been opened");   
     fclose(fp); 
    }  
    else printf("File not found"); 
    return 0; 

} 
+0

同樣,如果回答工作,然後upvote答案 –

相關問題