2017-01-23 71 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

相关问题