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

  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 int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    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.

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, 10:46 AM
  4. how to check end of file ?
    By blue_gene in forum C++ Programming
    Replies: 1
    Last Post: 03-29-2004, 09:33 AM