c - 在 C 中以增量方式读取和写入长数据类型时出错
问题描述
我有以下代码:
#include <stdio.h>
#include <stdlib.h>
int main() {
long num = 0;
FILE *fptr;
if ((fptr = fopen("test_num.txt","r+")) == NULL){
printf("Error! opening file");
return -1;
}
fscanf(fptr,"%ld", &num);
// Increment counter by 1
num += 1;
printf("%ld\n", num);
fprintf(fptr, "%ld", num);
fclose(fptr);
return -1;
}
使用上述代码,我试图读取文件的内容,该文件始终存储一个 long 值,仅将值递增 1,然后用新的递增值覆盖文件的 lond 值。但是,我试图做到这一点,而不是在读/写之间关闭和归档。例如,工作流程/算法应如下所示:
Step 1: Open the file
Step 2: Read the long value from the file
Step 3: Increment the long value by 1
Step 4: Overwrite the long value of the file by new incremented value
Step 5: Close the file
但是,如果我使用上述代码,则输出值会在文件末尾附加增加的值,而不是覆盖。我试过用“w+”和“w”打开文件,但当然这些只适用于写入而不是读取上面提到的文件。谁能知道我可以做些什么来实现目标?
解决方案
答案恰好是:我需要将文件指针倒回到文件的索引 0,以便用增加的值覆盖文件的内容。正确的代码如下:
#include <stdio.h>
#include <stdlib.h>
int main() {
long num = 0;
FILE *fptr;
if ((fptr = fopen("test_num.txt","r+")) == NULL){
printf("Error! opening file");
return -1;
}
fscanf(fptr,"%ld", &num);
// Increment counter by 1
num += 1;
printf("%ld\n", num);
rewind(fptr); // Rewind to index 0 of the fptr
fprintf(fptr, "%ld", num);
fclose(fptr);
return -1;
}
推荐阅读
- android - 如何通过堆栈跟踪调试 Flutter Web?
- javascript - 将 request.body 转换为 json
- angular - 如何在 Typescript 中使用代理为新属性添加 getter
- sql - 如何压缩返回的具有多个角色的用户行
- logstash - Logstash - csv 内的嵌套 json
- architecture - YOLOv5:基本架构 - 在哪里可以找到?
- wordpress - 如何从 Gatsby WordPress 网站的页面内容查询中排除作者和日期
- php - mysqli 和 php 在中添加列
- web-scraping - 通过在实际数据中添加无用数据来妨碍网站解析
- postgresql - Postgresql/rails - 加入不同的值,或者只为不同的值创建重复的行