在 C 中增量读取和写入长数据类型时出错
Error with reading and writing long data type incrementally in 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 值.但是,我试图在不关闭的情况下执行此操作,并在 reading/writing 之间归档。例如,workflow/algorithm 应如下所示:
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;
}
重写文本文件的一部分有两种常用方法:
将 while 文件读入内存,进行更改,然后从头写回。
读取部分文件(例如逐行),即时进行更改,然后写入新的临时文件。然后将临时文件重命名为实际文件。
我有以下代码:
#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 值.但是,我试图在不关闭的情况下执行此操作,并在 reading/writing 之间归档。例如,workflow/algorithm 应如下所示:
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;
}
重写文本文件的一部分有两种常用方法:
将 while 文件读入内存,进行更改,然后从头写回。
读取部分文件(例如逐行),即时进行更改,然后写入新的临时文件。然后将临时文件重命名为实际文件。