I need to get my data from the file that looks like this:
and then print it on my screen.
I cant figure how to print it because of dashes (-).
I tried this code:
typedef struct studenti {
char index[10];
char ime[20];
char prezime[20];
int kviz[10];
} studenti;
void init_load() {
int i;
studenti studenti;
FILE *fp;
fp = fopen("studenti_2022.txt", "r");
if(fp == NULL){
printf("Doslo je do greske");
return 0;
}
while(fread(&studenti, sizeof(studenti), 1, fp)){
printf("%s", studenti.index);
printf("%s", studenti.ime);
printf("%s", studenti.prezime);
printf("%d", studenti.kviz);
}
fclose(fp);
}
CodePudding user response:
fread is generally intended for reading binary data, and is usually the wrong function to use for a text formatted file. Unless you have written your structures directly to a file using fwrite, you will need something else.
In this case, you can use functions like fgets, fgetc, and fscanf to treat the contents of the file as text, and parse a known format.
strtok can be used to further tokenize a string, and strtol / sscanf can be used to read integers from those tokens.
Here is a rough example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char index[10];
char ime[20];
char prezime[20];
int kviz[10];
} student_info;
int get_next_entry(student_info *si, FILE *f) {
if (3 != fscanf(f, "%9sss", si->index, si->ime, si->prezime))
return 0;
char buffer[256];
if (fgetc(f) != '\n' || !fgets(buffer, sizeof buffer, f))
return 0;
size_t i = 0;
char *tok = strtok(buffer, "|");
if (tok) do {
si->kviz[i ] = (int) strtol(tok, NULL, 10);
} while (i < 10 && (tok = strtok(NULL, "|")));
/* make sure we read enough ints, and our delimiting line is there. */
if (i != 10 || !fgets(buffer, sizeof buffer, f) ||
0 != strncmp(buffer, "----------", 10))
return 0;
return 1;
}
int main(void) {
FILE *file = fopen("data.txt", "r");
student_info info;
if (file) while (get_next_entry(&info, file)) {
printf("%s\n%s\n%s\n", info.index, info.ime, info.prezime);
for (size_t i = 0; i < 10; i )
printf("%d ", info.kviz[i]);
putchar('\n');
}
fclose(file);
}
data.txt:
I-0123-45
John
Doe
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
--------------------------------------
I-0042-99
Jane
Doe
1 | 4 | 3 | 2 | 14 | 6 | 3 | 8 | 1 | 11 |
---------------------------------------
Output:
I-0123-45
John
Doe
1 2 3 4 5 6 7 8 9 10
I-0042-99
Jane
Doe
1 4 3 2 14 6 3 8 1 11

