Programming C: Posts 14 – Import and export files in C / C ++

During the programming process, we often have to read and write data to a file. This article will guide you how to make simple with C and C ++.

Noted: In the example below, the input and output files in the same folder with the source files.

Example: Cho file input.txt, The first line consists of 1 n is the number of friends, n the next line of each line is the name of 1 friend. Output.txt file read and write the list of friends included the serial number
input.txt output.txt
3
Nguyen Van Quan
Nguyen Thi Hong Anh
Nguyen Van Hung
1.Nguyen Van Quan
2.Nguyen Thi Hong Anh
3.Nguyen Van Hung

Code C

#include <stdio.h>

int main()
{
	int n, i;
	char name[255];							// khai bao bien ten
	FILE *fi = fopen("input.txt", "r");		// mo file de doc
	FILE *fo = fopen("output.txt", "w");	// mo file de ghi

	fscanf(fi, "%d", &n);					// doc so n tu file fi

	fgets(name, 255, fi);					// loai bo dau xuong dong sau khi doc so n

	for(i = 0; i < n; i++) 
	{					
		fgets(name, 255, fi);				// doc chuoi gom 255 ky tu tu file fi
		fprintf(fo, "%d.%s", (i+1), name);	// ghi chuoi ra file fo
	}

	fclose(fi);		// dong file fi
	fclose(fo);		// dong file fo

	return 0;
}

Code C++

#include <fstream>
using namespace std;

int main()
{
	int n;
	string name;
	ifstream fi("input.txt"); 	// mo file de doc
	ofstream fo("output.txt"); 	// mo file de ghi
	
	fi >> n;					// doc 1 so tu file
	getline(fi, name);			// loai bo dau xuong dong sau khi doc so n

	for (int i = 0; i <n; i++)
	{
		getline(fi, name);		// doc 1 dong tu file
		fo << (i+1) << "." << name << '\n';		// ghi 1 dong ra file
	}

	fi.close();
	fo.close();

	return 0;
}