0

C で 2 つのファイルをマージし、最後に停止します。

プログラムがありますが、ファイルが終了した後も単語を綴り続けます。例えば:

ファイル 1:

a
b
c

ファイル 2:

1
2
3
4
5

そして、私が得る結果は次のとおりです。

a
1
b
2
c
3
c
4
c
5

そして私が欲しい:

a
1
b
2
c
3
4
5

私の問題は、ループ内の私のifステートメントだと思います。whileそれを定義する方法がわかりません。

私のコードは次のとおりです。

#include <stdio.h>
#include <stdlib.h>


int main(void) {

    char d[200];                        //char för da.txt
    char h[200];                        //char för hej.txt
    FILE *hptr, *dptr;

    hptr = fopen("hej.txt", "r");       //Öppna hej.txt => hptr
    dptr= fopen("da.txt", "r");         //Öppna da.txt => dptr

    /*
    if(((hptr) == NULL && (dptr) == NULL)) //Fall 1 
    {
        printf("Error, båda filerna är tom");
        exit(1);
    }


    if ((hptr) == NULL)                 //Fall 2 när hej.txt är tom
    {
        fscanf(dptr,"%[^/]", d);        //Hämtar från da.txt
        printf("\nFil 2:\n%s", d);      //Skriver ut från da.txt
        exit(1);
    }

    if ((dptr) == NULL)                 //Fall 3 när da.txt är tom
    {
        fscanf(hptr,"%[^/]", h);        //Hämtar från hej.txt
        printf("Fil 1:\n%s", h);        //Skriver ut från hej.txt
        exit (1);
    } */

    if(hptr != NULL || dptr != NULL)        //Fall 4 när ingen fil är tom
    {

        while (!feof (hptr) && !feof (dptr))
        {
            if (hptr ***I guess this is the problem*** == feof)
            {
            fgets(d, 200, dptr);
            printf("%s", d);
            }

            if (hptr == feof)  
            {
            fgets(h, 200, hptr);
            printf("%s", h);
            }

        }

        fclose (hptr);
        fclose (dptr);
    }
    //getch();
    return EXIT_SUCCESS;
}
4

4 に答える 4

0

実際にはこれが必要です:

  if (hptr != NULL && dptr != NULL)        //Fall 4 när ingen fil är tom
  {               //^ you need && here, not ||

    do
    {
        if (fgets(d, 200, dptr) != NULL)
          printf("%s", d);

        if (fgets(h, 200, hptr) != NULL)
          printf("%s", h);
    } while (!(feof(hptr) && feof(dptr)));

    fclose(hptr);
    fclose(dptr);
  }

この SO の質問を参照してください: Why is “while ( !feof (file) )” always wrong?

于 2016-12-08T15:25:08.057 に答える
-1

必要はありませんfeof()(ひどい! ) 。2 つの入力ファイルを交互に使用して、fgets() の戻り値を使用するだけです。

#include <stdio.h>

int main(void)
{
char buff[100];
int state;

FILE * one, *two;
one = fopen("one", "r" );
two = fopen("two", "r" );

if (!one || !two) return 1;

for (state=0; ; state ^=1 ) {
        if (!fgets( buff, sizeof buff, state ? two: one)) break;
        printf("%s", buff);
        }

while (fgets( buff, sizeof buff, state? one : two)) {
        printf("%s", buff);
        }
fclose(one);
fclose(two);

return 0;
}
于 2016-12-08T15:26:13.627 に答える