问题描述
我正在使用fread函数从文件读取字符串,然后打印字符串。
我将字符串定义为具有LONGNUM大小(预定义值)的字符数组。
我每次读取1个元素,每个字节1个字节。
在使用以下命令打印字符串时:printf(读取的字符串为:%s\n,buffer);
的输出是:读取的字符串是b
我不明白,为什么在字符串结尾最后得到这个值?
当使用以下命令打印字符串时:printf(读取的字符串为:%c\n,buffer [0]);
我得到没有值的写输出。
请向我解释原因。
I'm reading from file to string with fread function and then printing the string.I defined the string as array of chars with LONGNUM size(pre defined value).I'm reading 1 element 1 byte size each time.when printing the string with : printf("the string that read is: %s\n",buffer);the output is : the string that read is bI don't get it, why in the end of the stringi get this values?when printing the string with : printf("the string that read is : %c\n",buffer[0]);I get the write output without values.please explain me why.
代码为
#include <stdio.h>
#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 <source path> <dest path>\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]);
}
}
我想要您告诉我什么是写方法。
谢谢。
I would like you to advise me what is the write way to do it.Thanks.
推荐答案
%s说明符期望空终止字符串。 fread不会以null终止字符串,因此您看不到正确的输出。由于缓冲区的长度为1,因此%c是要打印的正确说明符。
%s specifier expects null termination string. fread does not terminate string with null, so you don't see correct output. since buffer is of length 1, %c is the correct specifier to print.
这篇关于用%s打印字符串会打印错误的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!