Skip to content

Instantly share code, notes, and snippets.

@EdThePro101
Created January 12, 2021 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EdThePro101/552176ffcdf345c4ad153f2560e55305 to your computer and use it in GitHub Desktop.
Save EdThePro101/552176ffcdf345c4ad153f2560e55305 to your computer and use it in GitHub Desktop.
File IO operations in C.
// file-io.h
//
// #ifndef FILE_IO_H
// #define FILE_IO_H
//
// // Read and write files.
// // filename - The file's name.
// // buffer - Buffer that will contain file characters.
// // buffer_length - The length of the buffer.
// //
// // Returns 1 if any error has occurred.
// char fio_read(const char* filename, char* buffer, unsigned long int* buffer_length);
// char fio_write(const char* filename, char* buffer, unsigned long int* buffer_length);
//
// #endif
// If file-io.h is present, you may uncomment this line.
// #include "file-io.h"
// Include FILE operations and IO functions
#include <stdio.h>
#include <stdlib.h>
// Read a file.
// filename - Name of file.
// buffer - Buffer that will contain file output.
// buffer_length - Length of the buffer.
//
// Returns a value of 1 if an error occurred, otherwise returns 0.
char fio_read(const char* filename, char* buffer, unsigned long int* buffer_length) {
// Open the file for reading.
FILE* file = fopen(filename, "r");
// If the file could not be opened, print an error and return 1.
if (file == NULL) {
fprintf(stderr, "Error: Can't read file %s.\n", filename);
fclose(file);
file = NULL;
return 1;
}
// Get the file's length and store it in buffer_length.
fseek(file, 0L, SEEK_END); // Go to the end of the file.
*buffer_length = ftell(file); // Store the file's length.
fseek(file, 0L, SEEK_SET); // Go to the start of the file.
// Loop over file's characters one-by-one and store them in the buffer.
for (unsigned long int i = 0; i < *buffer_length; ++i) {
*(buffer + i) = (char) fgetc(file);
}
// No errors occurred.
return 0;
}
// Write a file.
// filename - The file's name.
// buffer - The input buffer.
// buffer_length - The length of the input buffer.
//
// Returns 1 if error.
char fio_write(const char* filename, char* buffer, unsigned long int* buffer_length) {
// Open the file for writing.
FILE* file = fopen(filename, "w");
// If the file couldn't be opened, print an error and return 1.
if (file == NULL) {
fprintf(stderr, "Error: Couldn't write file %s.\n", filename);
fclose(file);
file = NULL;
return 1;
}
// Write to the file character-by-character.
for (unsigned long int i = 0; i < *buffer_length; ++i) {
fputc(file, *(buffer + i));
}
// No errors occurred.
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment