I try to read text file looks like
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.
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);
}
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.