Segfault on ifs?

Hi - I have a piece of code that is supposed to do a basic display of text files:

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
 
#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;

int main(int argc, char **argv)
{
	char buf[100];

	if(argc==0)
	{
		cerr << "ERROR: Not enough parameters" << endl;
		cerr << "Syntax: " << argv[0] << "[file1] [file2] ... [fileN]" << endl;
		exit(1);
	}

	for(int i=1;i<argc;i++)
	{
		ifstream ifs;
		ifs.open(argv[i], ios::in);
		if (ifs.fail())
		{
			cerr << argv[0] << ": " << argv[i] << " No such file or directory" << endl;
		}
		else while(!ifs.eof())
		{
			ifs >> buf;
			cout << buf;
		}
	}
	exit(0);
}


There are two issues with it, however.

1. the program ignores the whitespace of whatever textfile it reads

2. I get segmentation fault errors on a certain file I'm supposed to test it with.

Thanks!
1. ifs >> buf reads till it find an space or a line break, and the separator is ignored.
You may want to use
1
2
std::string buf;
getline( ifs, buf );


2. More info is requested.

Also
1
2
if(argc==0) //I'm not sure that this could happen
  cerr << "Syntax: " << argv[0]; //but if argc is 0, then you don't have anything in argv 

Thanks for the help - my output is still getting stripped of its whitespace, though - as in, I want to output the text file such that it retains all of the original whitespace of whatever was in the file.
The reason your code segfaults is that your "certain file" almost certainly has input that will overrun your 100-byte buffer. One should not use stream operators with fixed size buffers. That C++ even allows it is a language defect IMO. Use read() with fixed size buffers.
Thanks, I changed it to such:

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
#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;

int main(int argc, char **argv)
{
	char buf[100];

	if(argc==0)
	{
		cerr << "ERROR: Not enough parameters" << endl;
		cerr << "Syntax: " << argv[0] << "[file1] [file2] ... [fileN]" << endl;
		exit(1);
	}

	for(int i=1;i<argc;i++)
	{
		ifstream ifs;
		ofstream ofs;
		ifs.open(argv[i], ios::in);
		if (ifs.fail())
		{
			cerr << argv[0] << ": " << argv[i] << " No such file or directory" << endl;
		}
		else while(!ifs.eof())
		{
			std:: string buf; 
			getline (ifs, buf);
			cout << buf;
		}
	}
	exit(0);
}


When output shows, however, I'm still getting all the text as one block without whitespace - would this be a cout problem?
Topic archived. No new replies allowed.