Skip to main content

File Input Output

Write

src/c/file-io/01-write-file.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// compile: gcc file.c -lm

int main()
{
int ii;
double theta, result1, result2;

FILE *fp;
fp = fopen("results.dat", "w");
if (fp == NULL)
{
printf("File could not be created.\n");
exit(1);
}

for (ii = 0; ii < 100; ii++)
{

theta = 4 * 3.14 * ii / 100;

if (theta == 0) // To avoid the 0/0 situation
{
theta = 0.000001;
}

result1 = sin(theta) / theta;
result2 = sin(2 * theta) / theta;

// printf("%f\t%f\n", theta, result);
fprintf(fp, "%f\t%f\t%f\n", theta, result1, result2);
}
fclose(fp);
return 0;
}

Read

src/c/file-io/02-read-file.c
#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 10

void read_file(FILE *fp, int data[], int *size)
{
*size = 0;
while (fscanf(fp, "%d", &data[*size]) == 1)
// fscanf returns 1 if success, 0 if fails
{
(*size)++;
}
}

void print_data(int data[], int size)
{
int i;
for (i = 0; i < size; i++)
{
printf("%d\n", data[i]);
}
}

double average(int data[], int size)
{
int i;
double average = 0.0;

for (i = 0; i < size; i++)
{
average += data[i];
}

return (average / size);
}

int main()
{
int i;
int size = MAX_SIZE;
FILE *fp;
int data[MAX_SIZE] = {0};

fp = fopen("file.dat", "r");
if (fp == NULL)
{
printf("File could not be opened.\n");
exit(1);
}

read_file(fp, data, &size);

printf("My %d scores are:\n", size);
print_data(data, size);

printf("Average score: %.2f\n", average(data, size));
fclose(fp);
return 0;
}

Append

src/cpp/file-io/03-append-file.cpp
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
// ofstream is used to write to file
ofstream fp_out{"data.txt"};

if (!fp_out)
{
cerr << "File could not be created!\n";
return 1;
}

for (int i = 1; i <= 10; i++)
{
fp_out << i << " " << i * i << endl;
}

fp_out.close();

// now we will open the file again to append more content
ofstream fp_app{"data.txt", ios::app};
// it is also possible to open the same fp_out
// fp_out.open("data.txt", ios::app};

if (!fp_app)
{
cerr << "File could not be created!\n";
return 1;
}

for (int i = 11; i <= 15; i++)
{
fp_app << i << " " << i * i << endl;
}

fp_app.close();
return 0;
}

Save buffer

Saving and reading buffer as binary is faster than IO using formatted data.

src/c/file-io/04-save-buffer.c
#include <stdio.h>
#include <stdlib.h>

int main()
{
int *base, x;
FILE *fp;

// allocate memory
base = (int *)malloc(sizeof(int) * 10);
if (base == NULL)
{
fprintf(stderr, "Failed to allocate memory.\n");
exit(1);
}

// fill with values
for (x = 0; x < 10; x++)
{
*(base + x) = x * 10;
}

// open file
fp = fopen("numbers.bin", "w");
if (fp == NULL)
{
printf("File could not be created.\n");
exit(1);
}

printf("%d\n", *(base + 1));
// save buffer to file
int size;
size = fwrite(base, sizeof(int), 10, fp);
// this returns number of items
// the data is written in the binary format as it exit in the buffer
printf("%d\n", size);
fclose(fp);
return 0;
}

Read buffer

src/c/file-io/05-read-buffer.c
#include <stdio.h>
#include <stdlib.h>

int main()
{
int *base, x, r;
FILE *fp;

// allocate buffer
base = (int *)malloc(sizeof(int) * 10);
if (base == NULL)
{
fprintf(stderr, "Error while allocating memory.\n");
exit(1);
}

// open file
fp = fopen("numbers.bin", "r");
if (fp == NULL)
{
fprintf(stderr, "Error reading file.\n");
exit(1);
}

// fill the buffer
r = fread(base, sizeof(int), 10, fp);
if (r != 10)
{
fprintf(stderr, "Could not read 10 numbers.\n");
exit(1);
}

// print values from buffer
for (int i = 0; i < 10; i++)
{
printf("%d\n", *(base + i));
}

return 0;
}