Skip to content

Instantly share code, notes, and snippets.

@EdThePro101
Created January 12, 2021 12:30
Embed
What would you like to do?
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