Reading files with \r\n

I'm having problems reading files with the Window's newline delimiter.

For some reason the fstream read command ignores all '\r' characters, but when counting the file length it will always include them. This leaves garbage characters at the end of the string when a file contains multiple lines of text.

Here's the relevant test code:

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
#define __NO_STD_VECTOR
//#include "CL/CL.hpp"
#include <iostream>
#include <fstream>

/**
 * Reads in a file and returns a string containing all the file text
 */
std::string readFile(const std::string& filename)
{
	std::fstream fileReader = std::fstream(filename.c_str(), std::ios_base::in);
	if(fileReader.is_open())
	{
		// find the length of the file
		std::streampos begin = fileReader.tellg();
		fileReader.seekg(0,fileReader.end);
		std::streampos end = fileReader.tellg();
		// return to the beginning and read the contents of the file
		fileReader.seekg(0,fileReader.beg);
		long length = end - begin;
		char *temp = new char[length+1];
		temp[length] = '\0';
		fileReader.read(temp, length);
		// put the contents into a string
		std::string result = std::string(temp, length);
		delete[] temp;
		temp = NULL;
		fileReader.close();
		return result;
	}
	return "";
}

int main(void)
{
	std::string fileText = readFile("count.cl");
	std::cout << fileText.c_str() << std::endl;
	std::cin.ignore();
	return 0;
}


This was tested on a file containing this text:
// this is a test kernel
kernel void test()
{
}

Here's the output: (notice that there are 3 garbage characters at the end)
// this is a test kernel
kernel void test()
{
}ÍÍÍ


Strangely enough, when I write back out to a file, the '\r' tokens mysteriously "re-appear" in the file.

Does anyone know why this is happening?

System specs: Windows 7 64-bit, compiled with VS2008 (the same output results regardless if compiled for 32-bit or 64-bit platforms).
Open the file in binary mode.

When you open in text mode (the default), it converts \r\n to \n when data is written. If you want raw, unchanged data, open in binary mode.
Thanks! That worked perfectly.

So I take it that even though opening a file in text mode converts \r\n to \n, the beg and end seek locations don't reflect this change?

What would you recommend for finding the number of characters that need to be read in if I did want to open in text mode?
Topic archived. No new replies allowed.