C编程-从文本文件中读取数字

标签 c scanf

我正在尝试制作一种数据库程序,但在从 C 文本文件中读取整数时遇到了一些问题。

我有以下代码:

#include <stdio.h>

int main(){
    int index;
    FILE * fp;

    if((fp = fopen("read_file.txt","r+")) == NULL){
        perror("Cannot open file");
        printf("\nCreating new file...");
        if((fp = fopen("read_file.txt","w+")) == NULL){
            perror("\nCannot create file.. Terminating..");
            return -1;
        }
    }
    fputs("INDEX = 3",fp);
    fscanf(fp, "INDEX = %d",&index);
    printf("index = %d\n",index);

    fclose(fp);
    return 0;
}

当我尝试运行程序时,它输出“index = 16”,我尝试使用 fgets 和 sscanf 但发生了同样的事情。然而,对于字符串,它决定打印出一堆没有意义的字符。

最佳答案

您在未定义行为中看到的内容是因为您将字符串写入文件并尝试扫描文件中不存在的 INDEX = %d,因为文件指针指向 之后索引 = 3

扫描前您需要快退(fp)

fputs("INDEX = 3",fp);
rewind(fp);
if( fscanf(fp, "INDEX = %d",&index) != 1)
printf("Scanning failes\n");
else
printf("INDEX = %d\n",index);

关于C编程-从文本文件中读取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28415024/

相关文章:

c - 尝试在循环中使用 scanf 扫描值。需要辅助输入来打印第一个输入

c - 分配大小为 char * 的内存有什么作用?

c - 使用gets函数输入

c - 如何使用 fscanf 将字符串放入数组?

c - sscanf() 返回部分前几行数据

c++ - 未声明的 Windows 中的 getchar_unlocked

c - 将二维数组传递给函数会返回意外的输出

c - C 中 switch 语句的开销

c - 使用字符串索引数组 (C)

c - Malloc 分配超出范围的内存地址