3.1 KiB
3.1 KiB
- Write a program to read a text file and display its contents on the screen.
- Write a program to copy the contents of a file into another.
- Write a program to read the class object of student_info such as name, age, sex, height and weight from the keyboard and to store them on a specified file using read() and write() functions. Again the same file is opened for reading and displaying the contents of the file on the screen.
Write a program to read a text file and display its contents on the screen.
#include <fstream>
#include <iostream>
using namespace std;
const string FILE_PATH = "./28.in";
int main() {
string line;
fstream file;
file.open(FILE_PATH, ios_base::in);
if (!file.is_open())
exit(1);
while (getline(file, line)) {
cout << line;
if (file.peek() != EOF) {
cout << endl;
}
}
file.close();
return 0;
}
Asperger syndrome (AS), also known as Asperger's, is a former neurodevelopmental disorder.
It is characterized by significant difficulties in social interaction and nonverbal communication.
Write a program to copy the contents of a file into another.
#include <fstream>
#include <iostream>
using namespace std;
const string SRC_FILE_PATH = "./29.in";
const string DST_FILE_PATH = "./29.out";
int main() {
string line;
fstream src, dst;
src.open(SRC_FILE_PATH, ios_base::in);
dst.open(DST_FILE_PATH, ios_base::out);
dst.close();
dst.open(DST_FILE_PATH, ios_base::app);
if (!src.is_open())
exit(1);
while (getline(src, line)) {
dst << line;
if (src.peek() != EOF) {
dst << endl;
}
}
src.close();
dst.close();
return 0;
}
Write a program to read the class object of student_info such as name, age, sex, height and weight from the keyboard and to store them on a specified file using read() and write() functions. Again the same file is opened for reading and displaying the contents of the file on the screen.
#include <fstream>
#include <iostream>
#include <ostream>
using namespace std;
const string FILE_PATH = "./30.out";
class StudentInfo {
char name[30];
uint age;
char sex;
uint height;
public:
void read();
void write();
};
void StudentInfo::read() {
cout << "Name: ";
cin >> name;
cout << "Age: ";
cin >> age;
cout << "Sex (m/f): ";
cin >> sex;
cout << "Height: ";
cin >> height;
cout << "[LOG] Data read\n";
}
void StudentInfo::write() {
ofstream file(FILE_PATH);
file.close();
file.open(FILE_PATH, ios_base::app);
file << "Name: " << name << endl
<< "Age: " << age << endl
<< "Sex: " << (sex == 'm' ? "Male" : "Female") << endl
<< "Height: " << height << "cm";
cout << "[LOG] Data written\n";
file.close();
}
int main() {
StudentInfo foo;
string line;
foo.read();
foo.write();
ifstream file(FILE_PATH);
if (!file.is_open())
exit(1);
cout << "File contents: \n";
while (getline(file, line)) {
cout << line;
if (file.peek() != EOF) {
cout << endl;
}
}
return 0;
}
Name: Hello
Age: 19
Sex (m/f): m
Height: 180
[LOG] Data read
[LOG] Data written
File contents:
Name: Hello
Age: 19
Sex: Male
Height: 180cm