c - 在文本文件中增加一个数字,语言 c

标签 c printf scanf fopen

<分区>

我下面的函数必须递增文件中的一个数字,该数字在开始时不存在。第一个“如果”是当文件为空时,第二个是在我的文件中制作“id++”并返回它,但是这个增量不起作用,如果我调用4次函数,它返回“0101” .感谢您的帮助。

int genererId(){
int id=0;
FILE * fichier = fopen("id.txt","w");
fclose(fichier);
fichier = fopen("id.txt","r");
if (fichier != NULL){

    if(fscanf(fichier,"%d",&id)!=EOF){
        fclose(fichier);
        FILE * fichier = fopen("id.txt","w");
        fprintf(fichier, "%d", 1);
        return 1;
    }else{
        printf("%d",id);
        fclose(fichier);
        FILE * fichier = fopen("id.txt","w");
        id++;
        fprintf(fichier, "%d",id);
        fclose(fichier);
        return id;
    }
}

return -1;
}


int main(){
    printf("%d",genererId());
    printf("%d",genererId());
    printf("%d",genererId());
    printf("%d",genererId());
    printf("%d",genererId());
    printf("%d",genererId());
    printf("%d",genererId());
}

当前输出:01010101010101 预期输出:1234567

最佳答案

我想你想要的是这样的:

#include <stdio.h>

int genID()
{
    int val ;
    FILE * fp = fopen("file.txt", "r") ;
    if (!fp) {
        fp = fopen("file.txt", "w") ;
        if (!fp) return -1 ; // fail
        fprintf(fp, "%d", 1) ;
        fclose(fp) ;
        return 1;
    }
    fscanf(fp, "%d", &val) ;
    val++;

    fclose(fp); // close file for read
    fp = fopen("file.txt", "w") ; // reopen for write
    fprintf(fp, "%d", val) ;
    fclose(fp) ;
    return val ;
}

int main() {
    printf("%d", genID()); // 1
    printf("%d", genID()); // 2
    printf("%d", genID()); // 3
    return 0 ;
}

下一次运行将得到 4、5、6 等。

关于c - 在文本文件中增加一个数字,语言 c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48329081/

相关文章:

c - printf:没有为格式字符串传递足够的参数

c - 如何从汇编代码中调用 C 函数 printf 获取整数

arrays - 在 C 中只打印一次数组中的所有元素?

c++ - MATLAB libpointer 数组

c - Linux内核线程: How to pass the Linux module write function as the function that the thread has to execute?

c - scanf 读取 "Enter"键

c - 从 c 中的 sscanf() 获取正确的格式

c - 带有可变参数的 scanf(C 语言)

python - 已解决 : C and Python: fill a file empty through mmap

c - 第一次通过后,recv()/send() 就乱序了