Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Files With Fstream: Short Answer

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Course: Programming Techniques (CSC10002)

20CLC3 – 20CLC6

FILES with FSTREAM

Short Answer

1. * What header file do you need to include in a program that performs file operations? // fstream
What data type do you use when you create a file stream object that can write data to a file? ofstream
How about creating a file stream object that can read data from a file? ifstream
để khi mình thực hiện các thao tác khác thì file gốc vẫn giữ
2. * Why should a program close a file when it has finished using it?nguyên và an toàn cho chương trình nếu như các lần sau
mình đọc file đó
3. * What are the differences among these classes, ifstream, ofstream and fstream?
reading/write/Khai báo header file
reading write

4. ** Show your experience when manipulating files with C++ fstream and C FILE class.
5. ** What task does each of the following code segments perform?
• ofstream ofile("file.txt"); tạo file có tên là file.txt sau đó ghi dữ liệu vào file. Cụ thể ở đây là:
goodmorning. Sau đó ghi ra màn hình dòng chữ" dât written to file"
ofile << "goodmorning" << endl;
cout << "Data written to file" << endl;
ofile.close();
• char data[100];
ifstream ifile("file.txt"); đọc dữ liệu từ file vào biến data sau đó xuất biến data ra màn hình
while ( !ifile.eof() ) {
ifile.getline (data, 100);
cout << data << endl;
}
ifile.close();
6. ** What is the content of the file “file.txt”after each of the following code segment executes?
• ofstream ofile("file.txt");
ofile << "hello new day", 13; nội dung của file là:
hello new month
ofile.seekp(9);
ofile << " month", 6;
ofile.close();
• ofstream outfile("file.txt");
outfile.write ("This is an apple",16);
long pos = outfile.tellp(); This is a sample

outfile.seekp (pos - 7);


outfile.write (" sam", 4);
outfile.close();

Nguyễn Ngọc Thảo – Bùi Huy Thông


1 HCMUS
7. ** The file expenses.txt contains the line: Hotel, 3 nights, $ 1750.25
Are the results of the two code segments below the same? If not, point out the difference(s).
ifstream in("expenses.txt"); ifstream in("expenses.txt");
char c; char c;
while (in.get(c)){ while (in.get(c)){
if (isdigit(c)) { if (isdigit(c)) {
in.unget(); in.unget();
double n; int n; 3
3
in >> n; in >> n;
cout << n << 'x'; cout << n << 'x';
} }
} }
8. ** Are the three following code
No
segments the same? If not, point out the difference(s).
ifstream in("file.txt"); ifstream in("file.txt"); ifstream in("file.txt");
char x; string x; string x;
int i{0}; int i{0}; int i{0};
while (in.get(x)) while (getline(in, x)) while (in >> x)
i++; //tựsốkhoảng
lượng kí tự trong file, kể cả kí
trắng
i++; // số lượng dòng ở trong file i++; // số lượng kí tự có trong file kể cả kí tự khoảng trắng
cout << i << endl; cout << i << endl; cout << i << endl;

9. ** There may be complie/runtime errors in the following code segment. Identify them.
• ifstream myStream;
ifstream.Open("file.txt", ios::out); // ifstream.open("file.txt",ios::in);

• int l;
char * b;
ifstream i;
i.open ("find.txt", ios :: binary ); // i.open("find.txt",ios::in|ios::binary);
i.seekg (0, ios :: end);
l = i.tellg();
i.seekg (0, ios :: beg);
b = new char [l];
i.read (b, l); sizeof(b)
i.close();
cout.write (b, l); sizeof(b)
delete[] b;
10. *** What screen output does each of the following code segments produce, and why?
• char character;
int integer;
ofstream out_stream;
ifstream in_stream;
/* Create a file containing two integers */
file Integers
out_stream.open("Integers"); 123 456
out_stream << 123 << '" " ' << 456;
out_stream.close();

Nguyễn Ngọc Thảo – Bùi Huy Thông


2 HCMUS
/* Attempt to read a character, then an integer, then a character
again, then an integer again, from the file "Integers". */
in_stream.open("Integers");
1 23
in_stream >> character >> integer;
1
cout << "character: '" << character << "'\n"; Output:
23 character: 1
cout << "integer: " << integer << "\n"; integer: 23
4 56
in_stream >> character >> integer; character: 4
4 integer: 56
cout << "character: '" << character << "'\n";
56
cout << "integer: " << integer << "\n";
in_stream.close();
• ofstream output; // ghi dữ liệu từ chương trình ra file scores.txt
output.open("scores.txt");
// Write two lines
output << "John" << " " << "T" << " " << "Smith" << " " << 90<<endl;
output << "Eric" << " " << "K" << " " << "Jones" << " " << 85;
File scores:
output.close(); John T Smith 90
Eric K Jones 85
ifstream input;
// Open a file // Mở file scores để đọc dữ liệu từ file vào chương trình
input.open("scores.txt");

// Read data
char firstName[80], lastName[80];
char mi;
int score;
input >> firstName >> mi >> lastName >> score;
90
double sum = score; Jones 85
Eric K
input >> firstName >> mi >> lastName >> score;
sum += score; 175
cout << "Total score is " << sum << endl;
input.close();
Total score is 175

Nguyễn Ngọc Thảo – Bùi Huy Thông


3 HCMUS
Fill-in-the-Blank

1. * Fill in each of the following blanks with an appropriate terminology


• ____________________
file's read position marks the location of the next byte that will be read from the file.
• This file access method is similar to the way cassette tape players work: _______________________.
sequential access

Meanwhile, this method is similar to the way a CD/MP3 player works: __________________________.
random file access

• The statement, _____________________________,


in>>word reads a single word from the ifstream named in
into the string variable word.
• You can use the ________________
seekp() function to move the file pointer for output and the ____________
seekg

function to move the file pointer for input. In these functions, the first argument indicates the
__________________
offset and the second argument indicates the ________________________.
mode

2. ** For each of the following cases, identify what the code segment will print out, given the content
of the input file.
• ifstream ifile("file.txt");
char last;
ifile.ignore (256, ' '); programming techniques
bỏ qua các kí tự cho đến khi gặp dấu cách thì dừng lại
last = ifile.get();
cout << "Your initial is " << last << '\n';
ifile.close();
The content of the file “file.txt” is "programming techniques"
What printed out is _____________________________________________________________________________
Your initial is t

• ifstream in("file.txt"); mở file ra để đọc dữ liệu từ file vào chương trình


char c;
int i = 0;
while (in.get(c)){
if (tolower(c) == 'a') i++;
} If I saw an Aardvark, I would scream!

cout << i << endl;


The content of the file “file.txt” is "If I saw an Aardvark, I would scream!"
What printed out is _____________________________________________________________________________
6

• ifstream in("file.txt");
char c;
while (in.get(c)){
if (isupper(c))
cout << toupper(c);
}
in.close();
The content of the file “file.txt” is "Orange Coast College"
What printed out is _____________________________________________________________________________
OCC

Nguyễn Ngọc Thảo – Bùi Huy Thông


4 HCMUS
• string word;
int i = 0;
ifstream read("file.txt");
while(read >> word){
if(i < word.length())
cout << word[i];
++i;
}
cout << endl;
The content of the file “file.txt” is
"The whole thing starts about twelve, fourteen or seventeen"
What printed out is _____________________________________________________________________________
Thirteen

3. ** Consider the following statement,


ofstream ofs;
ofs.open ("file.txt", _______________________);
ios::out

What should be filled in the blank so that the writing position starts at the end of the file?
4. ** The file grades.txt contains lines of text that look like this:
Smith 94
Jones 75
. . .
Each line of text contains the student's name (a single word) and an integer score.
Consider the following code segment,
string name;
int score;
ifstream in("grades.txt");
in>>name;
What is the legal way of reading one student's information?________________________________________
in>>score

5. *** The file grades.txt contains lines of text that look like this:
1 student1 3.5
2 student2 0.6
3 student3 4.0
4 student4 2.2
5 student5 2.3
. . .
Each line of text contains the student’s ID, name (a single word) and score.
Fill in the blanks in the following C++ code segment so that the code will read the text file above
to find a student with a specific ID and then print his/her name and GPA.

Nguyễn Ngọc Thảo – Bùi Huy Thông


5 HCMUS
string idToLookFor, id, name, gpa;
cout << "Enter student ID: ";
cin >> ____________________;
idToLookFor

_____________
ifstream din;
din.open( __________________
"grades.txt",ios::in );
if ( _______________
din.fail() )
cout << "Error. Unable to open file.\n";
else{
while((din >> id) && (id != idToLookFor))
din >> name >> gpa;
if ( ___________
id == idToLookFor ){
din >> ________________________ ;
name>>gpa

cout << "Student name: " << name << " GPA: " << gpa;
}
else
cout << "The student was not found." << endl;
din.__________;
close()

Nguyễn Ngọc Thảo – Bùi Huy Thông


6 HCMUS
True or False

Choose T (True) or F (False) for each of the following statements and then briefly explain in one or two
sentences.
1. T F There is no way to jump directly to the desired data in a text file.
2. T F The function eof is used for appending data to the end of a file.
3. T F It is possible to open several files for access at the same time.
4. T F If a file you are opening for appending does not exist, the operating system will detect the
missing file and terminate the operation.
5. T F If you create a file with the same name as an existing file, you will be always prompted to
rename your new file by the file creation function.
6. T F When you call an ofstream object’s open member function, the specified file will be
erased if it already exists. nội dung trong file bị xóa chứ không phải nó bị xóa
7. T F The return value of the getline function is an input stream object
8. T F The return value of the getline function is a string object.
9. T F If an input stream's file is missing when you try to open it, its member function fail
returns false.
10. T F If an output stream's file is missing when you try to open it, its member function fail
returns false.

Nguyễn Ngọc Thảo – Bùi Huy Thông


7 HCMUS
Algorithm Workbench

1. * Write a single statement to complete each of the following requirements


• Create an input file stream object named in and open the text file tuba.txt.
• Assume the text file tuba.txt contains several lines of text. Read one line from this file using
the input file stream object in
• Create an output file stream object named out and open the text file expenses.dat.
• Output the string “Hello Word” to the text file expenses.dat using the output file stream
object out.

2. ** Assume that the text file named Numbers.txt contains integers from 1 to 100 and these
numbers are separated by white blanks. Write code to read integers from the text file
Numbers.txt and output only prime numbers.
3. ** Write code to loop from 1 to 100 and write only Fibonacci numbers to the text file named
Fibonacci.txt.

Consider the following children poem as demonstration of text input data for Question 4 to 8.
i made myself a snowball
as perfect as could be
i thought i would keep it as a pet
and let it sleep with me
i made it some pajamas
and a pillow for its head
then last night it ran away
but first it wet the bed
Source: https://www.familyfriendpoems.com/poem/snowball-by-shel-silverstein

4. ** Write code to write the above content to the text file named Snowball.txt.
5. ** Write code to count the frequency of every distinct word in the text file Snowball.txt and store
these words (along with their frequencies), one per line, to a new text file named Freq.txt.
6. ** Write code to replace every instance of the word “it” in the text file Snowball.txt by the word
“snowball” and write the new content to the text file named newSnowball.txt.
7. ** Write code to receive a positive integer that is no larger than the number of lines in the text file
Snowball.txt and delete the corresponding line.
8. ** Write code to receive a positive integer that is no larger than the number of lines in the text file
Snowball.txt and insert the line “i love snowball” to the corresponding line.

Nguyễn Ngọc Thảo – Bùi Huy Thông


8 HCMUS
9. ** Consider the following two text files, FileA and FileB.
i never saw a purple cow the forest is the town of trees
i never hope to see one where they live quite at their ease
but i can tell you, anyhow with their neighbors at their side
i would rather see than be one just as we in cities wide
Merge these two files into a single file such that their lines come in an alternative fashion, that is,
the first line of FileA goes first and it is followed by the first line of FileB, and then the second
line of FileA and FileB, respectively, and so on.

10. *** Use some encryption algorithm to encrypt the file Snowball.txt and store the encrypted
content to the file Snowball.enc. After that, decrypt the previously encrypted file and store the
decrypted content to the file Snowball.dec .

Nguyễn Ngọc Thảo – Bùi Huy Thông


9 HCMUS

You might also like