使用%s打印字符串会打印错误数据

我正在使用fread函数从文件读取字符串然后打印字符串。 我将字符串定义为具有LONGNUM大小(预定义值)的字符数组。 我每次读1个字节1个字节的大小。 当打印字符串时:printf(“读取的字符串是:%s \ n”,缓冲区); 输出是:读取的字符串是b我没有得到它,为什么在stringi的最后得到这个值? 当打印字符串时:printf(“读取的字符串是:%c \ n”,缓冲区[0]); 我得到没有值的写输出。 请解释我原因。

代码是

#include  #define LONGNUM 1 void main(int argc,char *argv[]) { FILE * src; FILE * dst; int num; char buffer[LONGNUM]; // argc is the number of the elements in argv // the first argv element is the name of the program if(argc < 3){ printf("prototype error  \n"); return; } printf ("source path is : %s \n",argv[1]); printf ("dest path is : %s \n",argv[2]); src = fopen(argv[1],"r"); while(!(feof(src))){ num = fread(buffer,1,1,src); printf("the number of items read %d\n",num); printf("the string that read is %s\n",buffer); //printf("the string that read is %c\n",buffer[0]); } } 

我希望你告诉我这样写的方法是什么。 谢谢。

%s说明符期望空终止字符串。 fread不会终止带有null的字符串,因此您看不到正确的输出。 由于缓冲区的长度为1,因此%c是要打印的正确说明符。