Okay, file io in C requires the use of a FILE*. All it is is a pointer to a file. You declare a FILE* just like you would any other variable, and you use fopen set a file. Namely, it opens the file up, and returns the address of the file. That way, the FILE* points to the file, and doesn't take up as much space as the entire file would. Since fopen returns a FILE* you can use it like this.
- Code: Select all
FILE* file = fopen("actual_file.txt", "r");
When calling fopen, it is given two strings. First one is the name of the file, and the second one is the mode in which you open it. Different modes do different things, for instance:
"r" - will only give you read permission (meaning any functions you call to write into the file won't work) and sets you at the beginning.
"w" - will write the file, but it clears the file of any contents, so you start with an empty slate. But, since it gives you write permission, you can use functions like fprintf.
"a" - appends the file, so it opens the file up, and puts the pointer to the end of the file. That way when you use fprintf, it will add to the file, instead of overwriting your text.
"r+" - opens the file up, and allows you to write and read. Only difference from "a" is that it sets the pointer to the beginning of the file.
"w+" - opens the file for update, but discards the contents, but this allows you to read (unlike "w").
"a+" - like "w" and "w+" it sets read and write, and places you at the end of the file.
You can also append b to indicate if the file is a binary file.
Now that you have an opened file, and a handle to it, you can use the read and write functions. I'd suggest using fscanf and fprintf since most users are more familiar with how sprintf works. I can go into depth about the fprintf and fscanf functions if you want me to, but I think that's more straightforward. All it really is is writing data in a format that you can then do the reverse read operation. So, when you save data, make sure to save it in a specific format, that way you can use an fscanf to load back all the information you saved. One thing to note though is when saving information, you will usually use "w" as your fopen setting, and when you are loading information, you use "r".
And when you are done using a FILE*, so when you are done loading from it, or saving into one, you use fclose to close it.
- Code: Select all
fclose(file);