首页 > 解决方案 > 在 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”打开文件,但当然这些只适用于写入而不是读取上面提到的文件。谁能知道我可以做些什么来实现目标?

标签: cintegerfopenread-write

解决方案


答案恰好是:我需要将文件指针回到文件的索引 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;

}

推荐阅读