Avoid duplicates at the end of the file during read

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Andr3w
    New Member
    • Nov 2007
    • 42

    Avoid duplicates at the end of the file during read

    Hi,

    I was working on something when I noticed that the following code produced a duplicate char before reaching at the end of the file if it had a blank line (with no chars at the file) before the end of the file and without it, it would run file.

    [code=c]
    int ReadFromFile(in t argc, char **argv)
    {
    // our file pointer, initialized at NULL
    FILE *fStream = NULL;

    char buf[10];
    char p;
    int i = 0;

    if( (fStream = fopen(argv[1], "r")) == NULL )
    {
    // error, return the function
    return FALSE;
    }

    while( !feof( fStream ) )
    {
    fscanf(fStream, "%c", &p);


    if(p != '\n')
    {
    buf[i] = p;
    i++;
    }else {
    buf[i] = '\0';
    i = 0;
    }

    printf("%c", p);

    }


    return TRUE;
    }
    [/code]

    The input file has the following lines

    lol
    asdf
    mmd
    (here was the blank line)

    the output was:

    lol
    asdf
    mmdd

    if the blank line was present, when it didn't have that line the output was
    lol
    asdf
    mmd

    Why does this happen I have an idea but I've tried to make a workaround and came at a dead end... Any help?

    Update: found a workaround but still I can't explain to myself why the above code fails to provide the output I like... The workaround is the following code

    [code=c]
    int ReadFromFile(in t argc, char **argv)
    {
    // our file pointer, initialized at NULL
    FILE *fStream = NULL;

    char strBuf[20];
    char intBuf[10];
    char p;
    int i = 0, j = 0;

    if( (fStream = fopen(argv[1], "r")) == NULL )
    {
    // error, return the function
    return FALSE;
    }

    do
    {
    p = fgetc(fStream);

    strBuf[i] = p;
    i++;

    if(p == '\n' || p == EOF)
    {
    strBuf[i-1] = '\0';
    i = 0;
    }

    }while( !feof(fStream) );



    return TRUE;
    }
    [/code]

    I am sure the problem lies with fscanf but I can't figure why this is happening...
  • oler1s
    Recognized Expert Contributor
    • Aug 2007
    • 671

    #2
    Try answering a few questions for me, and we'll see where to go from there.

    1. How does feof work? How do you know it works like that?

    2. For fscanf, you require a character. What if someone types in value fit for a double instead? What would fscanf do? How do you know that fscanf did not receive something that could be translated as a character?

    3. Buffer takes in 9 characters, right? What if someone types in 21 chars, and then hits enter. What happens in your code?

    4. Are you aware of the function fgets? What does it do?

    5. Yet another question: what is the return value of fgetc? Why is it so?

    Comment

    Working...