C分割字符数组从文件中读取\ n(换行符),奇怪的输出

时间:2015-07-15 09:43:32

标签: c arrays

我正在将原始文本文件读入字符数组,然后我想基于“\ n”逐行拆分数据。我的代码是附加的,但我的输出非常奇怪。

INPUT FILE是在Windows上使用VIM创建的.txt文件,它看起来像:

london
manchester
britain
...

CODE(忽略一些var声明):

....
char * buffer = 0;
long length;
fl = fopen ("file.txt", "r");
if (fl){
  fseek (fl, 0, SEEK_END);
  length = ftell (fl);
  fseek (fl, 0, SEEK_SET);
  buffer = malloc (length);
  if (buffer){
    fread (buffer, 1, length, fl); 
  }
  fclose (fl);
  printf(buffer)
}else{
  printf("data file not found");
  return -1;
}

char str[80] = "london\nmanchester\nbritain";
char* entity = strtok(buffer, "\n");  //LINE-A, replacing 'buffer' with 'str' the output is correct.
while (entity != NULL) {
  printf("%s\n", entity);  //this prints strange output as shown below
  entity = strtok(NULL, "\n");
}

...

输出:

ondon
anchester
ritain

第一个角色总是丢失。

但是,如果我将“buffer”替换为“str”,则声明的字符数组与文件的内容相同,一切都按预期工作。

我不明白为什么我会收到此错误。请任何建议。

恩谢谢!

0 个答案:

没有答案
相关问题