cfileedit

Find the specified string in txt file and subtract the same value from the number


Goal: I use language C in Visual Studio 2022 to reduce the serial number by 7252 after “STORAGE_” in the file located at C:/Users/13383/Desktop/storage.txt. The data in storage.txt is as the following figure:

...

"STORAGE_7253":
...
"STORAGE_7254":
...
"STORAGE_7255":
...

Already done: my program as shown:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LINE_LENGTH 1000

int main() {
    FILE* fp;
    char line[MAX_LINE_LENGTH];
    char* pos;
    int num;

    if (fopen_s(&fp, "C:/Users/13383/Desktop/storage.txt", "r+") != 0) {
        printf("Error opening file\n");
        exit(1);
    }

    while (fgets(line, MAX_LINE_LENGTH, fp) != NULL) {
        pos = strstr(line, "STORAGE_");
        if (pos != NULL) {
            num = atoi(pos + strlen("STORAGE_"));
            printf("%d\n", num);
            num -= 7252;
            sprintf_s(pos + strlen("STORAGE_"), MAX_LINE_LENGTH - (pos - line) - strlen("STORAGE_"), "%d\"", num);
            puts(line);
        }
        //fputs(line, fp);
    }

    fclose(fp);
    printf("Done!\n");
    return 0;
}

Problem: When I comment out the fputs(line, fp);, I found the variable "line" contents the correct thing:

terminal picture

But when I uncommented "fputs" to write the strings in document, it prompted an error:

enter image description here

So I want to know what's the problem and how to fix it?


Solution

  • Easiest fix:

    Open "storage.txt" file read only - we'll call it ifile

    Open "new.storage.txt" file for output - we'll call it ofile

    Enter read loop from ifile

    Read line from ifile
    Process line
    Write line to ofile
    

    Close ifile

    Close ofile

    If new ofile created successfully, rename ifile to "yyyyMMddhhmmss.storage.txt" (where "yyyyMMddhhmmss" represents a datetime)

    Rename ofile to "storage.txt"

    It's always best to nondestructively update files, so writing a new file, then renaming the old file and renaming the new file is the prudent approach. If something goes wrong during file I/O operations, no harm, no foul.