简体   繁体   中英

confusion in read/write text file in c

I am trying to do some simple read/write in a .txt file. I write a function for reading the content, and another for write back the content-1.

For example, the content in the "counter.txt" is 20. After doing my code, I suppose the console output should show like:

index now is:20

index now is:19

But that shows 20 and 0, I don't understand why. Thanks for your help!

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

int read_data() {
    FILE *fptr;
    char *s;
    fptr = fopen("counter.txt","r");
    if (!fptr) {
        printf("fail to open..\n");
        exit(1);
    }

    fgets(s,25,fptr);
    fclose(fptr);

    return atoi(s);
}

void write_data(char *s) {
    FILE *fptr;
    fptr = fopen("counter.txt","w");
    if (!fptr) {
        printf("fail to open..\n");
        exit(1);
    }

    fputs(s,fptr);
    fclose(fptr);
}

int main(void) {
    char index_str[5];
    int index = read_data();
    printf("index now is:%d\n", index);
    sprintf(index_str,"%d",index-1);
    write_data(index_str);

    index = read_data();
    printf("index now is:%d\n", index);
    sprintf(index_str,"%d",index-1);
    write_data(index_str);
    return 0;
}

In read_data() , replace

char *s;

with

char s[200];

and you will have a valid s . This allocates 200 bytes on the stack, and you ( fgets() ) can safely write something there and use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM