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.
#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);
}
Example:
Enter a number: 5
Content in numbers.txt
1
2
3
4
5