Checking for an End Of Line in file

Hi,

I would like to check if my .txt file ends with a new line, and return an error if it doesn't.
What I have so far is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
	std::ifstream scriptFile; scriptFile.open(scriptPath); // Opening the output file
	if(!scriptFile.is_open()){ // If stream can't be openend 
		std::cout << "\n\tERROR\n";
		return 1;
	}

	while (scriptFile.good()){ // line comes from "char line[200];"
            scriptFile >> line; // avoiding to use getline(scriptFile,line) from <srting.h>
        }
	
	if (strncmp(line,"\r\n",1)!=0){ // last line of the file
		std::cout << "\n\tERROR line\n";
		return 1;
	}


And it doesn't want to work,
would you have any idea how to do that?
Thanks a lot,

Sky
Is this what you wanted?

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


#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

int main()
{
    ifstream inData;
    inData.open("test.txt");
    if(!inData.is_open())
    {
		cout << "\n\tERROR\n";
		return 1;
	}

    char buff[128], hold[1] = {'1'};
    bool empty = false;
    while (inData.getline(buff, 128))
    {
        strncpy(hold, buff, 1);
    }
    inData.close();
    if (!strlen(buff)) empty = true;
    cout << "Empty? " << empty << endl;
    return 0;
}


Tested with this file:

Line 1
2
3



7


Last edited on
I did not want to use cstring, but I guess I will need it for that...
Would it be possible for you to explain your code to me a little bit?
Why do you copy hold and buff?
Thank you very much though

Sky
Last edited on
You can't use getline (or >> ), because these extract the '\n' automatically. You want to use get().

It looks like get() works about the same way as the C getchar():

1
2
3
4
5
6
7
char ch;
char lastChar; // this is sort of like ToniAz' buffer

while ((ch = inFile.get()) ! = EOF) // Though not sure EOF is defined in iostream
  lastChar = ch;

if (lastChar != '\n') // fail. 


Line 4 reads a char and assigns it to ch, then checks if ch is not the EOF. While this is true, store ch in lastChar. We need two variables because we need one to check for EOF and one to hold real values.

I suppose you could use peek(), might even be easier?
1
2
while (inFile.peek())  // Triggers a fail bit for EOF
  lastChar = inFile.get();
It works like this!
Thank you very much!
Topic archived. No new replies allowed.