[英]Read characters with space characters from text file in C
我尝试读取文本文件看起来像
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]);
}
}
结果是:1020xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
但我希望它像图片一样。我哪里做错了? 谢谢你。
带有%s
fscanf()
将跳过空白字符。 您应该使用fgets()
来读取整行。
此外,您对while(!feof(file))
是错误的,您应该在使用“读取”之前检查读取是否成功。
另一个注意事项是在if
行中使用分号是不好的,因为它会禁用NULL
检查并让它在fopen
失败时尝试从NULL
读取内容。
尝试这个:
#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);
}
}
如果您真的想要 scanf/fscanf,请尝试"[^\\n]"
而不是"%s"
。 它将一直读取到行终止符 '\\n' 或文件的结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.