C splitting character array read from a file by \n (newline character), strange output -


i reading raw text file character array , want split data line line based on "\n". code attached, strange output.

input file .txt file created vim on windows, , looks like:

london manchester britain ... 

code (ignoring var declarations):

.... 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' 'str' output correct. while (entity != null) {   printf("%s\n", entity);  //this prints strange output shown below   entity = strtok(null, "\n"); } 

....

output:

ondon anchester ritain 

the first character missing.

however, if replace "buffer" "str" declared character array same content file works expected.

i not understand why getting error. advice please.

mnay thanks!

this may related fact aren't terminating string buffer. i'm unable produce exact problem unexpected characters in output. amend relevant lines of code follows , see if helps:

buffer = malloc(length + 1); if (buffer) {     fread(buffer, sizeof(char), length, fl);     buffer[length] = '\0'; } fclose(fl); 

if doesn't solve problem, might have weird (invisible) control characters in text file. try creating brand new 1 , see if problem still occurs.


Comments