[Legacy Content] This page contains very old information, which might not be valid anymore, they are only kept here for legacy purposes.
if you have any inquiries, feel free to contact me! Click here
Created: Monday, 12 August 2013 Written by Ehab Eldeeb
Included in this example:
- Structs
- Using Files
- While loop (obviously)
#include <stdio.h>
#include <conio.h>typedef struct { // define struct, this is a stock, write it just like that
char name[20]; // contents of the struct
int ID; // contents of the struct
float GPA; // contents of the struct
}Student; // struct name FOLLOWED BY A SEMICOLONvoid main(){
Student x;
FILE *f;
f = fopen("D:/db.txt", "r"); // open file for reading
while(feof(f) == 0){ // make sure the file didn't end
// foeof( pointer ) .. that means end of file pointed to by that pointer
fscanf(f, "%s%d%f", x.name, &x.ID, &x.GPA); // fscanf .. just like scanf but from file
printf("\n\nName: %s\nID: %d\nGPA: %f", x.name, x.ID, x.GPA); // print out what we read
}
fclose(f); // close the file to prevent corruption
getch();
}// Writing to file is just the same but in the fopen you write "w" instead of "r"
// There's also append "a" but you won't use it