2017-01-23 69 views
0
main() 
{ 
    char *temp_list[4096]; 
    char *list[4096]; 
    char *token,*token2 = NULL; 
    char *ptr; 
    int countries; 
    ssize_t rd_countries; 
    char temp_buf[512]; 
    char buf[512]; 
    size_t nbytes; 
    char *file_name = "AllCountries.dat"; 
    int temp = 0; 
    int temp2 = 0; 
    int i, j = 0; 

這裏我打開文件,然後再讀取它。如何使我的數據在使用讀取功能讀取文件時不會被截斷

countries = open(file_name,O_RDONLY); 
    nbytes = sizeof(buf); 

我然後做一個do-while循環讀取和標記化用逗號的數據,但512字節緩衝器大小夾子關閉數據以及添加了超過需要的。

do { 
     rd_countries = read(countries, buf, nbytes - 1); 
     if (rd_countries>-1) { 
      buf[rd_countries] = '\0'; 
     } 

     token = strtok_r(buf, ",", &ptr); 
     while (token != NULL) { 
      temp_list[i] = strdup(token); 
      printf("%s\n ||||||||||| ", temp_list[i]); 
      printf("%s\n", token); 
      token = strtok_r(NULL, ",", &ptr); 
      i = i + 1; 
     } 
    printf("-----------"); 
    } while (rd_countries != 0); 

下面是一些輸出。如您所見,東非變成東部A和非洲部分,而不是正確的輸出,因爲緩衝區會剪切它。

The temp list: IOT 
The temp list: British Indian Ocean Territory 
The temp list: Africa 
The temp list: Eastern A 
The temp list: frica 
The temp list: 78 
The temp list: NULL 
The temp list: 0 
The temp list: NULL 
The temp list: 0 
The temp list: British Indian Ocean Territory 
The temp list: Dependent Territory of the UK 
The temp list: Elisabeth II 
The temp list: NULL 
The temp list: IO 
+0

由於'buf'的大小,你會得到每512個字節的裁剪。我看不出有什麼理由爲什麼你會在你所做的事情上被剪輯。 – Barmar

+0

(文件是必須更大,我只是顯示了它剪輯的部分)是啊,我知道,但多數民衆贊成的要求,我只是想知道如何將文件指針移回到最後已知的「\ n」,但我不知道它出來 – jhowe

+1

你應該用'fstat()'得到文件的大小,然後爲整個文件分配一個足夠大的緩衝區並讀入它。 – Barmar

回答

0

立即讀取整個文件,而不是以512字節的塊讀取。您可以使用fstat()獲取文件大小。

struct stat statbuf; 
fstat(countries, &statbuf); 
buf = malloc(statbuf.st_size+1); 
rd_countries = read(countries, buf, statbuf.st_size); 
buf[rd_countries] = '\0'; 
+0

我必須使用512個字節的緩衝區 – jhowe

+0

如果您必須使用固定大小的緩衝區,則不能使用'strtok()',因爲無法知道它是否因爲到達緩衝區的末端而停止或因爲在緩衝區中有一個','。 – Barmar

+0

這是一個瘋狂的限制。 – Barmar

0

如果你有512字節的限制,那麼請遵循以下步驟。

  • 你需要在循環內部取一個變量byte2read,它將看到如何在512字節的緩衝區中留下很多字節。
  • 在while循環之後進行條件檢查,看看byte2read是否大於0.
  • 如果是,則在再次讀取文件時只讀512 - byte2read並將buf + byte2read作爲緩衝區的開始。
+0

那麼緩衝區將會是滿的,因爲文件中可能有10000個字節,所以它不會少於512個字節的讀取,直到到達EOF爲止? – jhowe

相關問題