Hey

I have a text file (1.txt) with the lines:

This is line 1
This is line 2
This is line 3
This is line 4
This is line 5

and Im trying to read all the pair lines from that file and write them to another text file called 2.txt which would result in this:

This is line 2
This is line 4

My code works but the problem is at the end it runs into a infinite loop and the result is

This is line 2
This is line 4
This is line 5
This is line 5
This is line 5
This is line 5
This is line 5
This is line 5
This is......

until I manually stop the program. I imagine there is something wrong with my EOF loop and/or the length I set. Also maybe the program doesnt know it should jump to the next line when it reads a /n or something. The variables are in spanish but I THINK they could be understood. If not, Ill translate

#include <assert.h>
#include <complex.h>
#include <ctype.h>
#include <errno.h>
#include <fenv.h>
#include <float.h>
#include <inttypes.h>
#include <iso646.h>
#include <limits.h>
#include <locale.h>
#include <math.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <wchar.h>
#include <wctype.h>

int main()
{
    FILE *archivopar;
    FILE *archivocopiado;
    char texto[50];
    int i=1;

    archivopar=fopen("archivopar.txt","r");
    archivocopiado=fopen("archivocopiado.txt","w");


    if ((archivopar==NULL) || (archivocopiado==NULL))
    {
        printf ("No se puede abrir algun archivo!");
        return 1;
    }
    else
    {
        do{
            fgets(texto,50,archivopar);
            if (i % 2 == 0)
            {
                fprintf(archivocopiado,"%s\n",texto);
            }
            if (archivopar!=EOF)
            {
                i=i+1;
            }
        }while(archivopar!=EOF);
        fclose(archivopar);
        fclose(archivocopiado);
        return 0;
    }
}

I know its problably something stupid but I cant figure it out. Thanks for the help.

Dani AI

Generated

Short diagnosis tied to the thread: the infinite loop and the repeated "This is line 5" come from two different mistakes. As noted, comparing a FILE* to EOF is wrong (EOF is an int returned by some I/O functions). Also, if you call fgets and then ignore its return value, you may keep printing the old buffer after EOF — that explains the repeated last line. Finally, the translated code that calls fgets twice per iteration causes you to skip/shift lines (so you only see 4th, 7th, etc.).

Correct, simple pattern
Use a single fgets per loop, increment the line counter only when fgets succeeds, and write the buffer as-is (fgets keeps the trailing newline). Example:

#include <stdio.h>

int main(void)
{
    FILE *in = fopen("filepairs.txt", "r");
    FILE *out = fopen("filecopied.txt", "w");
    char buf[BUFSIZ];
    int lineno = 0;

    if (!in || !out) return 1;
    while (fgets(buf, sizeof buf, in)) {
        lineno++;
        if ((lineno & 1) == 0)    /* even-numbered lines: 2,4,... */
            fputs(buf, out);
    }
    fclose(in);
    fclose(out);
    return 0;
}

Practical notes and pitfalls

  • Don’t use while (file != EOF) or if (file != NULL) inside the loop to detect EOF — use the return value of fgets (or fgetc/getline) instead.
  • Avoid fprintf(out, "%s\n", buf) because buf already usually ends with \n; that can add blank lines. If you need to normalize line endings, strip \r/\n (e.g., buf[strcspn(buf, "\r\n")] = '\0';) then write with a single \n.
  • Remove the dozens of unused headers; include only what you need (stdio.h, maybe string.h).
    Following the above fixes the infinite loop, prevents stale-buffer printing, and yields the expected even lines (2, 4, ...).

Recommended Answers

All 7 Replies

Change

do{
            fgets(texto,50,archivopar);
            if (i % 2 == 0)
            {
                fprintf(archivocopiado,"%s\n",texto);
            }
            if (archivopar!=EOF)
            {
                i=i+1;
            }
        }while(archivopar!=EOF);

to

while(fgets(texto,sizeof texto,archivopar))
         {
            if (i % 2 == 0)
            {
                fprintf(archivocopiado,"%s\n",texto);
            }
            if (archivopar!=EOF)
            {
                i=i+1;
            }
        }

...more or less.

Change

do{
            fgets(texto,50,archivopar);
            if (i % 2 == 0)
            {
                fprintf(archivocopiado,"%s\n",texto);
            }
            if (archivopar!=EOF)
            {
                i=i+1;
            }
        }while(archivopar!=EOF);

to

while(fgets(texto,sizeof texto,archivopar))
         {
            if (i % 2 == 0)
            {
                fprintf(archivocopiado,"%s\n",texto);
            }
            if (archivopar!=EOF)
            {
                i=i+1;
            }
        }

...more or less.

Thanks but now its just weird lol....

It copies in the file only the forth line and the seventh line...

Yup. It has to do with the incrementing of i. Why would it need to be conditional as you have it?

[edit]I suppose I should have pointed that out earlier. I guess that chunk of my play code didn't tag along with my post. I'd trimmed down unused headers and other things -- I tend to get carried away sometimes.

Hey

I have a text file (1.txt) with the lines:

This is line 1
This is line 2
This is line 3
This is line 4
This is line 5

and Im trying to read all the pair lines from that file and write them to another text file called 2.txt which would result in this:

This is line 2
This is line 4

My code works but the problem is at the end it runs into a infinite loop and the result is

This is line 2
This is line 4
This is line 5
This is line 5
This is line 5
This is line 5
This is line 5
This is line 5
This is......

until I manually stop the program. I imagine there is something wrong with my EOF loop and/or the length I set. Also maybe the program doesnt know it should jump to the next line when it reads a /n or something. The variables are in spanish but I THINK they could be understood. If not, Ill translate

#include <assert.h>
#include <complex.h>
#include <ctype.h>
#include <errno.h>
#include <fenv.h>
#include <float.h>
#include <inttypes.h>
#include <iso646.h>
#include <limits.h>
#include <locale.h>
#include <math.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <wchar.h>
#include <wctype.h>

int main()
{
    FILE *archivopar;
    FILE *archivocopiado;
    char texto[50];
    int i=1;

    archivopar=fopen("archivopar.txt","r");
    archivocopiado=fopen("archivocopiado.txt","w");


    if ((archivopar==NULL) || (archivocopiado==NULL))
    {
        printf ("No se puede abrir algun archivo!");
        return 1;
    }
    else
    {
        do{
            fgets(texto,50,archivopar);
            if (i % 2 == 0)
            {
                fprintf(archivocopiado,"%s\n",texto);
            }
            if (archivopar!=EOF)
            {
                i=i+1;
            }
        }while(archivopar!=EOF);
        fclose(archivopar);
        fclose(archivocopiado);
        return 0;
    }
}

I know its problably something stupid but I cant figure it out. Thanks for the help.

i dont know spanish but i hope u understand this..

the segments

if (archivopar!=EOF)

and

while(archivopar!=EOF);

are wrong.
archivopar is a FILE pointer and EOF is -1 these will never get equal.
i mean the comparision is wrong.

fgets returns the address of the next line read. And incase if there is no line i.e whenit reaches EOF, it returns the NULL, so you better compare the return address of the fgets to check whether it reached EOF.
NOTE:
fgets read atmost size -1(here 50 -1 = 49) characters including '\n'. and '\n' will be placed in the array when read characters are less than size-1.

char *temp;

                temp=fgets(texto,50,archivopar);
                           if (temp!=NULL)
                 while(temp!=NULL);

it will work with the above changes.

copies only line with even numbers.

Gaiety I did not understand what you mean/said so here is the code translated:

#include <assert.h>
#include <complex.h>
#include <ctype.h>
#include <errno.h>
#include <fenv.h>
#include <float.h>
#include <inttypes.h>
#include <iso646.h>
#include <limits.h>
#include <locale.h>
#include <math.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <wchar.h>
#include <wctype.h>




int main()
{
    FILE *filepairs; //This pointer points to the file that contains the "this is line 1" etc 
    FILE *filecopied; //This pointer points to where the lines will be copied to
    char text[50]; //A string array
    int i=1; //a counter

/* Opening the files */
    filepairs=fopen("filepairs.txt","r");
    filecopied=fopen("filecopied.txt","w");


    if ((filepairs==NULL) || (filecopied==NULL))
    {
        printf ("One of the files cannot be opened!");
        return 1;
    }
    else
    {
        while (fgets(text,sizeof text,filepairs))
        {
            fgets(text,50,filepairs);
            if (i % 2 == 0)
            {
                fprintf(filecopied,"%s\n",text);
            }
            if (filepairs!=NULL)
            {
                i=i+1;
            }
        }
        fclose(filepairs);
        fclose(filecopied);
        return 0;
    }
}

I hope this clears it up for everyone. Thanks to everyone for trying to help out :)

Just increment i for every line read, right?

Gaiety I did not understand what you mean/said so here is the code translated:

try your code with this input:

(i)
filepairs.txt:
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7

you will get out put as :
This is line 4

(ii)
filepairs.txt:
This is line 0
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6

you will get out put as :
This is line 3
This is line 7

Find out whats worng

please explain when the belowstatement becomes false and what is the need of that.

if (filepairs!=NULL)

I hope this clears it up for everyone. Thanks to everyone for trying to help out

the program is not correct yet....!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.