2017-04-14 53 views
0

我需要循環槽目錄,data和讀取每個文件,滿足一定的條件下,在一個字符串,用它做什麼。出於某種原因,它的fseek呼叫失敗後(輸出目錄中的第一個文件的唯一名稱)。FSEEK()和FTELL()在一個循環中失敗

任何想法,我究竟做錯了什麼?

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

void doAlgorithm(char *input) { 
    printf("%s\n", input); 
} 

int main(int argc, char** argv) { 
    struct dirent *dir; 
    DIR *d = opendir("data"); 
    FILE *file; 
    while ((dir = readdir(d)) != NULL) { 
     if (strlen(dir->d_name) > 6 && dir->d_name[6] == 'i') { 
      printf("Filename: %s\n", dir->d_name); 
      file = fopen(dir->d_name, "r"); 
      fseek(file, 0, SEEK_END); 
      long length = ftell(file); 
      fseek(file, 0, SEEK_SET); 
      printf(", Filesize: %ld\n", length); 

      char *buffer = malloc(length + 1); 
      fread(buffer, 1, length, file); 
      buffer[length] = '\0'; 

      fclose(file); 
      doAlgorithm(buffer); 
     } 
    } 
    closedir(d); 
    return (EXIT_SUCCESS); 
} 
+0

'ftell'返回'long' int太小 –

+0

你也無法檢查返回值到處都是。僅僅因爲你要求「長度」字節並不意味着你拿到了它們。 – ShadowRanger

+0

確定我固定的,但它仍然不會改變任何東西,程序仍不能正常的FSEEK()調用後工作。順便說一句,我在Windows上運行它,如果它很重要。 –

回答

0

您的問題是,您file = fopen(dir->d_name, "r");不知道該文件在目錄中的位置。你需要給它完整的路徑。你可以這樣做;

struct dirent *dir; 
    // put the directory path here. on windows is \ instead of/
    char *path = "/Users/adnis/CLion/Stackoverflow/testdir"; 
    char *slash = ""; 
    DIR *d = opendir(path); 
    FILE *file; 
     while ((dir = readdir(d)) != NULL) { 
     if (strlen(dir->d_name) > 6 && dir->d_name[6] == 'i') { 
       printf("Filename: %s\n", dir->d_name); 
       int length = strlen(path); 
     /*check if the path already contains a '/' at 
      the end before joining the filename to the directory*/ 

       if(path[strlen(path)-1] != '/'){ //on windows is '\' 
        slash = "/"; 
       } 

       length += strlen(dir->d_name)+2; 
    // allocate memory for the new path 
    // and make sure we have enough memory. 
       char *newpath = malloc(length); 

       assert(newpath != NULL); 

       snprintf(newpath,length,"%s%s%s",path,slash,dir->d_name); 

       file = fopen(newpath, "r"); 
       if(file == NULL){ 
        fprintf(stderr, "fopen: %s\n", strerror(errno)); 
        break; 
       } 
       fseek(file, 0, SEEK_END); 
       long len = ftell(file); 
       fseek(file, SEEK_SET, 0); 

       char *buffer = malloc(len + 1); 
       fread(buffer, 1, len, file); 
       buffer[strlen(buffer)] = '\0'; 

       printf("%s \n",buffer); 
       fclose(file); 
      } 
     } 
     closedir(d); 
     return (EXIT_SUCCESS); 

我建議,當閱讀目錄時,你還必須儘量避免閱讀「。」。和「..」,因爲它們只是當前目錄和上一個目錄。像這樣的事情會有所幫助。在你的while循環中

if(strcmp(dir->d_name,".") == 0 || strcmp(dir->d_name,"..") == 0) 
      continue;