-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathExercise 9.4 (Completed)
88 lines (74 loc) · 2.34 KB
/
Exercise 9.4 (Completed)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
1. (Practice) A function named pFile() is to receive a filename as a reference to an ifstream
object. What declarations are required to pass a filename to pFile()?
// within the main() function
string fname = "pass.dat";
void pFile(ifstream&);
ifstream inFile;
inFile.open(fname.c_str());
pFile(inFile);
// within the pFile function
void pFile(ifstream& fileIn){
}
2. (Practice) Write a function named fcheck() that checks whether a file exists. The function
should accept an ifstream object as a formal reference parameter. If the file exists, the function
should return a value of 1; otherwise, the function should return a value of 0.
int fcheck(const std::string& name)
{
std::ifstream infile(name);
return infile.good();
}
3. (Practice) A data file consisting of a group of lines has been created. Write a function named
printLine() that reads and displays any line of the file. For example, the function called
printLine(fstream& fName,5); should display the fifth line of the passed object stream.
void printLine(ofstream& fileOut, int n)
{
const int NUMLINES = 7; // number of lines
int count;
string line;
cout << "Please enter five lines of text : " << endl;
for (count = 0; count < NUMLINES; ++count)
{
getline(cin, line);
if (count == n){
fileOut << line << endl;
}
}
cout << "\nThe file has been successfully written.";
return;
}
4. (Modify) Rewrite the getOpen() function used in Program 9.9 to incorporate the file-checking
procedures described in this section. Specifically, if the entered filename exists, an appropriate
message should be displayed. The user should be given the option of entering a new filename
or allowing the program to overwrite the existing file. Use the function written for Exercise 2
in your program.
bool fcheck(const std::string& name)
{
std::ifstream infile(name);
return infile.good();
}
int getOpen(ofstream& fileOut)
{
string name;
char letter;
cout << "\nEnter a filename : ";
getline(cin, name);
if (fcheck(name) == true){
cout << "File Exist"<< endl;
cout << "Enter new file name Y/N" << endl;
cin >> letter;
if (letter == 'Y'){
cout << "\nEnter a filename : ";
getline(cin, name);
}
else{
fileOut.open(name.c_str());
}
}
fileOut.open(name.c_str()); //
if (fileOut.fail()) // check for successful open
{
cout << "Cannot open the file" << endl;
}
else
return 1;
}