0

I try to read text file looks like

mytextfile

int main() 
{
FILE *file;

char k[200][2];
int i=0;

if((file=fopen("blobs1.txt","r"))!=NULL);
{
        
    while(!feof(file))
    {
     fscanf(file,"%s",&k[i]);
     printf("%s",k[i]);
         
    
}
    
}

and result is:1020xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

but I want it to be like the picture.Where am I doing wrong ? Thank you.

2 Answers2

0

fscanf() with %s will skip whitespace character. You should use fgets() to read whole lines.

Also your usage of while(!feof(file)) is wrong and you should check if readings are successful before using what are "read".

Another note is that having semicolon in the if line is bad because it will disable the NULL check and have it try to read things from NULL when the fopen fails.

Try this:

#include <stdio.h>

int main(void)
{
    FILE *file;

    char k[200][2];
    int i=0;

    if((file=fopen("blobs1.txt","r"))!=NULL)
    {
        
        while(fgets(k[i], sizeof(k[i]), file) != NULL)
        {
            printf("%s",k[i]);
            
        
        }
        
        fclose(file);
    }
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
0

If you really want scanf/fscanf, try "[^\n]" instead of "%s". It will read until the line terminator '\n' or end the of the file.

Gabriel
  • 106
  • 4