Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // FILE I/O EXAMPLE - C
- // (c) gigabytemon
- // 26/06/2020
- // 2862 abc5 66cb a008 dbd9 5bf7 0dda 04f8
- // e192 33e4 e689 4efb 24b9 d34f 6c2d 1ee1
- /* introduction
- * ------------
- * file i/o only involves a few steps that need to be taken
- * 1) declaring the file object, i.e. what we will use to refer to the file
- * 2) opening the file, and in what mode (read, write, append, etc)
- * 3) performing operations on the file (write to, read from)
- * 4) closing the file
- *
- * it's important to know that some read operations will stop when it finds a space ( )
- * while others will only stop at the end of the line (\n)
- * also, write operations will overwrite the contents of a file unless opened explicitly
- * in append mode.
- */
- #include <stdio.h>
- void writingToFile() {
- //declare file object
- FILE *fp; //this is a pointer, pointing to a FILE object that we are calling fp
- //we must open the file before we can do anything
- // >> object = fopen("filename", "access mode")
- fp = fopen("C:/project_files/test.txt", "a+");
- /* access modes:
- * r = for reading only
- * w = for writing (overwrite) only (creates file if it doesnt exist)
- * a = for writing in append mode (creates file)
- * r+ = for reading and writing (overwrite)
- * w+ = for reading and writing (overwrite) (creates file)
- * a+ = for reading and writing (append mode)
- */
- //writing to file
- // >> fprintf(object, "string")
- fprintf(fp, "Wrote this string using fprintf. \n");
- // >> fputs("string") << doesn't need object reference
- fputs("Wrote this string using fputs. \n");
- //close the file after using it
- // >> fclose(object)
- fclose(fp);
- }
- void readingFromFile() {
- //declare file object
- FILE *fp;
- //declare a character buffer for the strings we will read from the file
- char buffer[255];
- //open the file in read mode
- fp = fopen("C:/project_files/test.txt", "r");
- //reading from file
- // >> fscanf(object, "%s", destination)
- //NOTE: THIS WILL ONLY READ UNTIL IT ENCOUNTERS A SPACE (BLANK CHARACTER)
- fscanf(fp, "%s", buffer);
- printf("Line 1: %s\n", buffer);
- // >> fgets(destination, buffer size, (FILE*)object)
- //NOTE: THIS WILL READ UNTIL END OF LINE
- fgets(buffer, 255, (FILE*)fp);
- printf("Line 2: %s\n", buffer);
- //close the file
- fclose(fp);
- }
- void main() {
- writingToFile();
- readingFromFile();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement