簡體   English   中英

嘗試從二進制文件讀取文本文件時,數組未出現在文本文件中

[英]My array does not appear in my text file when i try to read it from my binary file

#include<stdio.h>
#include<conio.h>

typedef struct {
      char CNP[14];
      char nume[30];
      int an;
      int grupa;
      int nrDiscipline;
      char note[20];
} STUDENT;

void main() {
    FILE*f;
    char numef[20];
    STUDENT s;
    printf("Nume fisier:"); gets(numef);
    f = fopen(numef, "rb");
    if (!f)
        printf("eroare");
    else {
        FILE*g;
        fopen_s(&g,"stud.txt", "w");
        fread(&s, sizeof(STUDENT), 1, f);
        while (!feof(f)) {
            fprintf( g,"%s %s %d %d %d ", s.CNP, s.nume, s.an, s.grupa, s.nrDiscipline);
            for (int i = 0; i < s.nrDiscipline; i++)
            {
                fprintf(g, "%s", s.note[i]);   
            }

            fread(&s, sizeof(STUDENT), 1, f);
        }
        fclose(g); fclose(f);

    }

}

首先,我創建了二進制文件,該文件運行良好,但是隨后我打開了文本文件,數組不正確,它似乎包含一些隨機數,可能還有一些地址。 我嘗試了一切,但沒有用。

更換

  fread(&s, sizeof(STUDENT), 1, f); while (!feof(f)) { ... fread(&s, sizeof(STUDENT), 1, f); } 

通過

    while (fread(&s, sizeof(STUDENT), 1, f) == sizeof(STUDENT)) {
        ...
    }

這有幾個優點:

大概修改fprintf(g, "%s", s.note[i]); fprintf(g, "%s ", s.note[i]); 分隔注釋,除非您真的想寫很長的行,否則添加fputc('\\n', g); 同時的端

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM