Home > Software engineering >  How i can create a function for reading structure from a test.txt
How i can create a function for reading structure from a test.txt

Time:12-01

How i can create a function for reading structure from a test.txt. I have a good works code in main, but i need to carry out it from main(). How combine (struct student PI1[N] and (fread() or fgets() or fwrite()));

struct student {
    char surname[50];
    char name[50];
    char dayBirth[50];
    int mark;
};

struct student PI1[N];
int main()
{
    
    int counter = 0;
    char str[50];
    const char s[2] = " ";
    char* token;
    FILE* ptr;
    int i = 0;

    ptr = fopen("test.txt", "r");

    if (NULL == ptr) {
        printf("file can't be opened \n");
    }
    char* tmp;
    int Itmp;

    while (fgets(str, 50, ptr) != NULL) {
        token = strtok(str, s);
        strcpy(PI1[i].surname, token);

        token = strtok(NULL, s);
        strcpy(PI1[i].name, token);

        token = strtok(NULL, s);
        strcpy(PI1[i].dayBirth, token);

        token = strtok(NULL, s);
        Itmp = atoi(token);
        PI1[i].mark = Itmp;
        i  ;
        counter  ;
    }
}

CodePudding user response:

Rather than "can create a function for reading structure from a test.txt", start with a function to convert a string from fgets() into a struct. Then call it as needed.

Use sprintf() and " %n" to detect complete scan with no extra text.

// Return success flag
bool string_to_student(struct student *stu, const char *s) {
  int n = 0;
  sscanf(s, "IsIsIs%d %n", stu->surname, stu->name,
      stu->dayBirth, &stu->mark, &n);
  return n > 0 && s[n] == '\0';
}

Use

while (i < N && fgets(str, sizeof str, ptr) && 
    string_to_student(&PI1[i], str)) {
  i  ;
}
counter = i;

CodePudding user response:

The most efficient solution is, to store your structs in a binary file.
Additionaly, you don't have to care about formats etc.

Writing:

FILE* fp;
struct student;

fp = fopen("test.txt", "wb");
fwrite(&student, 1, sizeof(student), fp);
fclose(fp);

Reading:

FILE* fp;
struct student;

fp = fopen("test.txt", "rb");
fread(&student, 1, sizeof(student), fp);
fclose(fp);

(Didn't write error checking for the sake of simplicity)

  • Related