Created
October 21, 2012 07:49
-
-
Save jmdeldin/3926261 to your computer and use it in GitHub Desktop.
Line Endings in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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