Skip to content

Instantly share code, notes, and snippets.

@jmdeldin
Created October 21, 2012 07:49
Show Gist options
  • Save jmdeldin/3926261 to your computer and use it in GitHub Desktop.
Save jmdeldin/3926261 to your computer and use it in GitHub Desktop.
Line Endings in C++
/**
* reader.cc -- demonstrate the inanity of line endings
*
* compile with
* g++ -Wall -ansi -pedantic reader.cc -o reader
* run it with
* ./reader some_file.txt
*
* You can create Windows line endings in Vim with :se ff=dos and Unix files
* with :se ff=unix (or run dos2unix and unix2dox on a text file).
*/
#include <string>
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;
void chomp(string& str)
{
string::size_type pos = str.find_last_not_of("\r\n");
str.erase(pos + 1);
}
void read(char* filename)
{
ifstream inputStream;
inputStream.open(filename);
if (!inputStream) {
cerr << "Unable to open file" << endl;
exit(1);
}
const int MAX_SIZE = 80;
char buf[MAX_SIZE];
while (inputStream.getline(buf, MAX_SIZE)) {
string s = buf;
// If we didn't chomp, the \r from Window's newlines (\r\n) would be
// in our string
chomp(s);
cout << s << "EOL?" << endl;
}
cout << endl;
}
int main(int argc, char* argv[])
{
if (argc != 2) {
cerr << "Usage: ./reader FILE" << endl;
exit(1);
}
read(argv[1]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment