c - 用 %s 打印字符串打印出错误的数据

标签 c string char printf fread

我正在使用 fread 函数从文件读取到字符串,然后打印该字符串。 我将字符串定义为具有 LONGNUM 大小(预定义值)的字符数组。 我每次都在读取 1 个元素 1 个字节大小。 打印字符串时:printf("读取的字符串是:%s\n",buffer); 输出是:读取的字符串是 b 我不明白,为什么在 stringi 的最后得到这个值? 打印字符串时:printf("读取的字符串是:%c\n",buffer[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]);

    }

}

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

最佳答案

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

关于c - 用 %s 打印字符串打印出错误的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41327919/

相关文章:

c# - 如何在 C# 中比较字符的简短方式

c - GCC 扩展类型

c++ - 如何连接并打印字符串的每个元素?

c - C中的初始化字符串

regex - Perl 正则表达式问题!

c# - 无法将类型 'string' 隐式转换为 'System.Windows.Forms.ColumnHeader

c++ - 如何将 std::string 转换为 const char* 或 char*

c - 为什么不能将注册变量设置为全局变量?

c - C 中递归的递归

c - 错误: derefrencing pointer to incomplete type