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

时间:2016-12-26 07:34:59

标签: c string char printf fread

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

代码是

#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]);

    }

}

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

1 个答案:

答案 0 :(得分:1)

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

相关问题