How can I check if there is a newline character at the end of my file?

This is a discussion on How can I check if there is a newline character at the end of my file? within the C Programming forums, part of the General Programming Boards category; I've tried a couple things but none of them work. Can anyone show me how to do this please? This ...

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    31

    How can I check if there is a newline character at the end of my file?

    I've tried a couple things but none of them work. Can anyone show me how to do this please?

    This is what I've tried so far. It is a regular text file, opened with "a+".

    Code:
    fseek(filepathA,-2,SEEK_END);
    char newlinetest=fgetc(filepathA);
        if (newlinetest >=' ' && newlinetest <='~')
        fputc((int)'\n',filepathA);
    fseek(filepathA,0,SEEK_SET);
    Also I tried...
    Code:
    fseek(filepathA,-2,SEEK_END);
    char test;
    test=fgetc(filepathA);
    if (test==10)
    printf("\nyes, there is a newline there\n");
    else
    printf("no, there isn't one");

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Have you tried using -1 instead of -2?

    By the way, using fseek() on text files is undefined.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Jan 2009
    Posts
    31
    I have tried that. So what do you suggest I do?

  4. #4
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,344
    What about some results?

    What about some input files you tested with?

    What about improving the error checking on the functions you're already using?

    Posting a handful of lines and "it doesn't work" is not a quality bug report.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 04:27 PM
  3. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 09:46 AM
  4. how to check end of file ?
    By blue_gene in forum C++ Programming
    Replies: 1
    Last Post: 03-29-2004, 08:33 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21