【问题标题】:fscanf printing replacement characterfscanf 打印替换字符
【发布时间】:2021-12-30 21:28:21
【问题描述】:
#include <assert.h>
#include <ctype.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
    
    //opening collection.txt using ptr 
    FILE *ptr;
    
    char data[1000];
    ptr = fopen("collection.txt", "r");
    
    printf("Hello world \n");
    
    fscanf(ptr, "%s", data);
    printf("%s \n", data);
    
    fclose(ptr);
    
    return 0;       
}

collection.txt:

hi my name is 

当我运行这个程序时,我得到:

Hello world 
P7k

P7k 是我假设的内存位置。

我查看了多个网站和文章,但无法弄清楚如何打印 collection.txt 中的文本

【问题讨论】:

  • 添加检查 fopen 是否成功:if (ptr == NULL) { printf("Could not open file\n"); return 1; } 另外总是检查所有 scanf 的功能(如 fscanf)returns。
  • @Someprogrammerdude 使用了 if 条件,但没有运气:(检查了 fscanf 的返回值,但没有多大帮助
  • fopen 是否成功,ptr 在fopen 调用后不是空指针?而fscanf 返回1?
  • @Someprogrammerdude 是的,我确实做到了,但不是运气。是的 fscanf 返回 1
  • 还将fscanf(ptr, "%s", data); 替换为fgets(data, sizeof(data), ptr); 看看会发生什么。

标签: c pointers scanf


【解决方案1】:

问题包括

未测试 fopen() 成功

FILE *ptr;
// add
if (ptr == NULL) {
  fprintf(stderr, "Fail to open\n");
  return -1;
}

未测试 fscanf() 成功

// fscanf(ptr, "%s", data);
if (fscanf(ptr, "%s", data) != 1) {
  fprintf(stderr, "Fail to read\n");
  return -1;
}

不限制输入

char data[1000];
// fscanf(ptr, "%s", data);
fscanf(ptr, "%999s", data);

未报告所有数据

"%s" 不保存空白,因此不会打印文件中的空白。

使用fgets() 读取输入的行。要阅读所有内容,请使用循环。

while (fgets(data, sizeof data, ptr)) {
  printf("%s", ptr);
}

【讨论】:

    【解决方案2】:

    %s 只扫描直到找到一个白色字符。我的建议是逐字符扫描文件 (%c),直到到达文件末尾。

    类似:

    while(!feof(ptr)) { 
      fscanf(ptr, %c, data + counter); counter++;
    }
    

    【讨论】:

    • 请正确格式化您的答案。
    • 代码有溢出ptr的风险。当循环完成时,data[] 肯定还不是一个 string,因为没有附加 null 字符,导致下面的 printf("%s \n", data); 出现 UB。
    猜你喜欢
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    相关资源
    最近更新 更多