About C language file input/output

Asked 2 weeks ago, Updated 2 weeks ago, 2 views

#include <stdio.h>
#include <string.h>

int main()
{
    FILE* rfp;
    FILE* wfp;
    char aa[200];
    char bb[200];
    int change;

    rfp = fopen("file1.txt", "r");
    wfp = fopen("file2.txt", "w");

    while (1)
    {
        fgets(aa, 200, rfp);
        //fscanf(rfp, "%s", aa);

        change = strlen(aa);

        if (feof(rfp))
            break;

        for (int i = 0; i < change; i++)
        {
            bb[i] = aa[(change - 1) - i];

        }
        bb[change] = '\0';

        fprintf(wfp, "%s\n", bb);
        //fputs(bb, wfp);
    }

    fclose(rfp);
    fclose(wfp);

    return 0;
}

Enter the string of file1 upside down, as shown above I made a code to print it out to file2.

Why does the fgets(aa, 200, rfp); function leave a space at the top, as in file2?

I understand that the other part of the gap is due to the fgets() function reading up to '\n'.

I don't understand the blank at the top

file1

Visual
Studio Professional
Basic-C
Study

file2

 (There is a space here now)
lausiV
(Blank)
lanoisseforP oidutS
(Blank)
C-cisaB
(Blank)
ydutS

c

2022-09-20 08:56

1 Answers

The fgets function reads a line from a file containing '\n'.

Therefore, the first time file1 is read, "Visual\n" is read into array aa, and the string is replaced with "\nlausiV" because it is relocated backwards. Output from this state results in a new line (\n) + "lausiV".


2022-09-20 08:56

If you have any answers or tips


© 2022 pinfo. All rights reserved.