home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C Programming Starter Kit 2.0
/
SamsPublishing-CProgrammingStarterKit-v2.0-Win31.iso
/
tybc4
/
io1.cpp
< prev
next >
Wrap
C/C++ Source or Header
|
1993-04-05
|
2KB
|
89 lines
// C++ program that demonstrates sequential file I/O
#include <iostream.h>
#include <fstream.h>
#include <string.h>
enum boolean { false, true };
const unsigned LINE_SIZE = 128;
const unsigned NAME_SIZE = 64;
void trimStr(char* s)
{
int i = strlen(s) - 1;
// locate the character where the trailing spaces begin
while (i >= 0 && s[i] == ' ')
i--;
// truncate string
s[i+1] = '\0';
}
void getInputFilename(char* inFile, fstream& f)
{
boolean ok;
do {
ok = true;
cout << "Enter input file : ";
cin.getline(inFile, NAME_SIZE);
f.open(inFile, ios::in);
if (!f) {
cout << "Cannot open file " << inFile << "\n\n";
ok = false;
}
} while (!ok);
}
void getOutputFilename(char* outFile, const char* inFile,
fstream& f)
{
boolean ok;
do {
ok = true;
cout << "Enter output file : ";
cin.getline(outFile, NAME_SIZE);
if (stricmp(inFile, outFile) != 0) {
f.open(outFile, ios::out);
if (!f) {
cout << "File " << outFile << " is invalid\n\n";
ok = false;
}
}
else {
cout << "Input and output files must be different!\n";
ok = false;
}
} while (!ok);
}
void processLines(fstream& fin, fstream& fout)
{
char line[LINE_SIZE + 1];
// loop to trim trailing spaces
while (fin.getline(line, LINE_SIZE)) {
trimStr(line);
// write line to the output file
fout << line << "\n";
// echo updated line to the output window
cout << line << "\n";
}
}
main()
{
fstream fin, fout;
char inFile[NAME_SIZE + 1], outFile[NAME_SIZE + 1];
getInputFilename(inFile, fin);
getOutputFilename(outFile, inFile, fout);
processLines(fin, fout);
// close streams
fin.close();
fout.close();
return 0;
}