mpgn
mpgn

Reputation: 7251

C detect the last new line at the end of the file

I can't detect the new line after just before the end of the file if the new line have text on the previous line.

I can detect the new line 4

1  some text
2  some text
3
4

But not the new line 3 with this type of file

1  some text
2  some text
3

(the number (1,2,3,4) are the lines, they are not in the file)

There is my sample code : (edit: code is updated with more relevant variable)

#include <stdio.h>
#include <string.h>

main()
{
   FILE *fp;
  int ch;
  int i = 0;
  int line = 1;
  int column = 0;
  int tmp = 0; 
   fp = fopen("input.txt", "r");
   if( fp != NULL ){
      while((ch = fgetc(fp)) != EOF) {
        switch(ch) {

          case '\n':
              if(i == 0) {
                  column = tmp;
              }
              if(tmp != column) {
                printf("error\n");
              }
              tmp = 0;
              line++;
              i++;

              break;
          default:
              tmp++;
              break;
        }
      }
      fclose(fp);
   }
}

I don't understand why there is not output "error" in the second case.

Upvotes: 0

Views: 1190

Answers (2)

Farouq Jouti
Farouq Jouti

Reputation: 1667

I think that by understanding what a newline character is you will understand what's wrong let's see the content of the file while showing the newline the first file actually like this

1  some text\n
2  some text\n
3  \n
4  empty

not like this

1  some text\n
2  some text\n
3  \n
4  \n

and the second one is like this

1  some text\n
2  some text\n
3  empty

Upvotes: 0

John Bollinger
John Bollinger

Reputation: 181909

Your code counts the number of characters in the file before the first newline, and stores it as n. Each subsequent time it reads a newline, it checks whether the number of characters read since the previous newline is the same as the number of characters on the first line (n), and prints an error message if not (which seems a bit odd).

Have you considered where the newlines are in your input, and what exactly the definition of a "line" is? I think you will find that there are three newlines in the four-line text, and two in the three-line text. That is, what your editor is presenting to you as the last line of the file is not itself terminated by a newline.

Upvotes: 1

Related Questions