C++ File I/O

Introduction

File I/O (Input/Output) is used to read data from a file and write data to a file.
We usually stores data in a file for future use.
fread() and fwrite() functions are used to read and write data from/to a file.

Example:

FILE *fp;
fp = fopen("file.txt", "w");
fprintf(fp, "Hello World!");
fclose(fp);

This code will write "Hello World!" to a file named file.txt.
fp is a pointer to a FILE object, which is used to access the file.
fopen() function is used to open a file. The first argument is the name of the file, and the second argument is the mode in which the file is opened. "w" mode is used to write to a file.
fprintf() function is used to write data to a file.
fclose() function is used to close the file.

To read data from a file, we use fread() function.

Example:

FILE *fp;
char str[100];
fp = fopen("file.txt", "r");
fread(str, sizeof(char), 100, fp);
fclose(fp);
cout << str;

This code will read the content of file.txt and display it to the user.
str is an array of characters that will store the content of the file.
fread() function is used to read data from a file. The first argument is the array where the data will be stored, the second argument is the size of each element, the third argument is the number of elements to read, and the fourth argument is the file pointer.

Code - Save user input to a file

#include <iostream>
using namespace std;

int main() {
	FILE *fp;
	char str[100];
	fp = fopen("file.txt", "w");
	cout << "Enter a string: ";
	cin.getline(str, 100);
	fprintf(fp, "%s", str);
	fclose(fp);
}
	

Task

Ask the user to enter a number. Save numbers from 1 to n to a file named numbers.txt.
One line for each number.
Hint: use a for-loop to write numbers to the file.

Example:

Enter a number: 5
Content in numbers.txt
1
2
3
4
5

Reference

programiz