Basic
Practice Problems based on chapter which you learn in previous Tutorials.
1. Write a Sentence in File
#include <stdio.h>
Copy Code
int
main
() {
int
num1, num2;
printf
("Enter the first number: ");
scanf
("%d", &num1);
printf
("Enter the second number: ");
scanf
("%d", &num2);
int
sum = num1 + num2;
printf
("Sum: %d
", sum);
return
0;
}
The
fopen
function is used to open a file named "
example.txt
" in write mode ("w").
If the file is successfully opened, the program writes the sentence to the file using
fprintf
.
Finally, the fclose function is used to close the file.
2. Read the First line
#include <stdio.h>
Copy Code
int
main
() {
std::ifstream
inputFile("example.txt");
if
(!inputFile.is_open()) {
std::cerr
<<
"Error opening the file!"
<< std::endl;
return
1;
}
std::string
firstLine;
std::getline
(inputFile, firstLine);
inputFile
.close();
std::cout
<<
"First line from the file: "
<< firstLine << std::endl;
return
0;
}
The
fopen
function is used to open the file named
"example.txt"
in read mode ("r").
If the file is successfully opened, the program uses
fgets
to read the first line from the file into the line buffer and if the file is empty, a message indicating that the file is empty is printed and the
fclose
function is used to close the file.