繁体   English   中英

继续读取文件的第一行

[英]Keeps reading the first line of file

该程序在文件的同一行写入一个int和一个string 然后我需要读取那个intstring并分配给一些变量。 我已经设法按预期将数据写入文件,但是当我尝试读取和存储它时,似乎我要么只是一遍又一遍地读取第一行,要么我以错误的方式存储.

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

struct cliente {
    char nome[50];
    int nif;
};

int main(void) {
    FILE * fptr;
    int i = 0;
    int quantidade = 0;
    int j = 0;

    fptr = fopen("clientedata", "w");

    if (fptr != NULL) {
        printf("File created successfully!\n");
    } else {
        printf("Failed to create the file.\n");
        // exit status for OS that an error occured
        return -1;
    }
    printf("insira a quantidade: ");
    scanf("%d", & quantidade);
    struct cliente client[quantidade];

    for (i = 0; i < quantidade; i++) {
        fptr = fopen("clientedata", "a");
        printf("Enter clientedata name: ");
        scanf(" %[^\t\n]c", client[i].nome);
        printf("Enter clientedata NIF: ");
        scanf("%d", & client[i].nif);
        if (i == 0) {
            fprintf(fptr, "%d %s", client[i].nif, client[i].nome);
        } else fprintf(fptr, "\n%d %s", client[i].nif, client[i].nome);
        fclose(fptr);
    }

    for (j = 0; j < quantidade; j++) {

        fptr = fopen("clientedata", "r");
        fscanf(fptr, "%d %s", & client[j].nif, client[j].nome);
        printf("NIF: %d\n", client[j].nif);
        printf("nome: %s\n", client[j].nome);
        fclose(fptr);
    }
    return 0;
}

这是代码和文件中的 output:代码和文件输出

是的 ! for循环中删除fopenfclose并在循环前后写入解决了问题! 谢谢!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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