2015-04-12 24 views
-1

我有一個包含以下文本稱爲test.txt的文本文件:從文本文件中給出的文件名/路徑檢查文件是否存在?

文件路徑/Desktop/file.txt

我所需要的單詞後的文件路徑來獲取路徑,並檢查如果該文件實際存在於文件系統中。我使用strchr()和strtok()從文本文件中提取「/Desktop/file.txt」,並將其與access()函數一起用於檢查是否存在。然而,它從來沒有真正起作用,並且說它並不是每一次都存在,即使它確實存在。

這是我的代碼的一部分,試圖讓這個工作。

char *buffer = 0; 
long length; 
FILE *getfile; 
getfile = fopen("test.txt", "r"); 

if (getfile){ 
    fseek (getfile, 0, SEEK_END); 
    length = ftell (getfile); 
    fseek (getfile, 0, SEEK_SET); 
    buffer = malloc (length); 
    if (buffer){ 
     fread (buffer, 1, length, getfile); 
     } 
    fclose (getfile); 
} 

char *getfilepath = (strchr(buffer, 'filepath') + 2); 

int filepathexists = access(getfilepath, F_OK); 

if(filepathexists == 0){ 
    printf("The file exists."); 
} else { 
    printf("File does NOT exist."); 
} 
+2

不能使用這麼長的字符'strchr'文字。一個proprer編譯器(或啓用正確的編譯標誌)應該警告「字符太長」。 – usr2564301

+3

您已閱讀文件末尾的換行符。文件名不包含換行符。如果根目錄有一個你可以訪問的'/ Desktop'子目錄,那麼除去換行符,代碼就會有效。你確定在'/'中有'/ Desktop'目錄嗎? (哦,並用換行符結束打印消息;這有助於確保消息顯示及時,並且不會與提示輸入下一個命令等相混淆) –

+2

另請注意,來自'fread()'的輸入不是將被終止爲你...所以它讀取一個字節數組而不是一個字符串。你需要從fread()中獲取返回值,這樣你才知道文件名是多長。 –

回答

0

這應該這樣做。文件輸入用fgets()讀取,關鍵字用strstr()進行測試。我使用strtok()來隔離路徑名與任何尾隨的newline等,但由於路徑可以包含空格,因此我一直在小心地檢查獨立的前導空格。注意:不要忘記你分配的內存爲free()

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <errno.h> 

int main(void) 
{ 
    int filepathexists = 0; 
    char *buffer, *sptr; 
    const char *cue = "filepath"; 
    size_t length; 
    FILE *getfile; 
    getfile = fopen("test.txt", "r"); 
    if (getfile){ 
     fseek (getfile, 0, SEEK_END); 
     length = ftell (getfile);     // find file size 
     fseek (getfile, 0, SEEK_SET); 
     buffer = malloc (length + 1);    // allow for str terminator 
     if (buffer){ 
      if (fgets(buffer, length + 1, getfile) != NULL) { 
       sptr = strstr(buffer, cue);  // cue in correct place 
       if (sptr == buffer) { 
        sptr += strlen(cue);   // skip past cue 
        while (*sptr == ' ')   // and leading spaces 
         sptr++; 
        sptr = strtok(sptr, "\r\n\t"); // isolate path from newlines etc 
        if (sptr) { 
         printf("The file is: %s\n", sptr); 
         if (access(sptr, 0) != -1) { 
          filepathexists = 1; 
         } 
        } 
       } 
      } 
      free (buffer); 
     } 
     fclose (getfile); 
    } 

    if (filepathexists) 
     printf("The file exists.\n"); 
    else 
     printf("File does NOT exist.\n"); 
    return 0; 
} 

程序輸出:

The file is: /Desktop/file.txt 
The file exists. 
相關問題