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
由于'buf'的大小,你会得到每512个字节的裁剪。我看不出有什么理由为什么你会在你所做的事情上被剪辑。 – Barmar
(文件是必须更大,我只是显示了它剪辑的部分)是啊,我知道,但多数民众赞成的要求,我只是想知道如何将文件指针移回到最后已知的“\ n”,但我不知道它出来 – jhowe
你应该用'fstat()'得到文件的大小,然后为整个文件分配一个足够大的缓冲区并读入它。 – Barmar