I want to read a string from two files and output it to a new file alternately with the first line of the file, the first line of the file, the second line of the file, and the second line of the file.

Asked 1 years ago, Updated 1 years ago, 32 views

I'd like to read strings from two files and output them to the new file alternately with the first line of the file, the first line of the file, the second line of the file, and the second line of the file.
I have three string arrays in my head, starting with the first file

#include<stdio.h>

int main(void){
    FILE*fp1,*fp2,*fp3;
    fp1 = fopen("1.txt", "r");
    fp2 = fopen("2.txt", "r");
    fp3 = fopen("4.txt", "w");

    inti = 0, j = 0;
    int n = 0, m = 0;
    chars[20][20];
    chat[20][20];
    charst [20][20];

    while(fscanf(fp1, "%s", s[i][20])!=NULL){
        st[2*i][20]=s[i][20];
        i++;
    }

    while(fscanf(fp2, "%s", t[j][20])!=NULL){
        st[2*(1+j)][20] = t[j][20];
        j++;
    }

    while(st[n][20]!=NULL){
        fprintf(fp3, "%s\n", st[n][20]);
        n++;
    }

    printf("Outputed";

    fclose(fp1);
    fclose(fp2);
    fclose(fp3);
    return 0;
}

c++

2022-09-30 20:17

2 Answers

If you incorporate the area,

#include<fstream>
# include <iostream>
# include <string>

int main() {
    std::ifstream f1 {"1.txt"}, f2 {"2.txt"};
    std::ofstream f3 {"4.txt"};
    for(std::string line; f1||f2;){
        if(f1&getline(f1,line))
            f3<<line<<std::endl;
        if(f2&getline(f2,line))
            f3<<line<<std::endl;
    }
}

That's about it.


2022-09-30 20:17

If you want to do it in the C range instead of C++, you will see the following:

fgets reads a line into the buffer (buf) and returns the string if successful.Returns NULL if it cannot be read due to file termination.Newline characters are also buffered.
http://www.c-tipsref.com/reference/stdio/fgets.html

Write a string with fputs.
http://www.c-tipsref.com/reference/stdio/fputs.html

#include<stdio.h>

int main()
{
    FILE*fp1,*fp2,*fp3;

    constint BUF_SIZE=20;
    char buf [BUF_SIZE];

    char*sz1,*sz2;

    fp1 = fopen("1.txt", "r");
    fp2 = fopen("2.txt", "r");
    fp3 = fopen("4.txt", "w");


    while(true)
    {
        sz1 = fgets(buf,BUF_SIZE,fp1);
        if(sz1!=NULL){
            fputs(sz1,fp3);
        }
        sz2 = fgets(buf,BUF_SIZE,fp2);
        if(sz2!=NULL){
            fputs(sz2,fp3);
        }
        if(sz1==NULL&&sz2==NULL){
            break;
        }
    }

    fclose(fp1);
    fclose(fp2);
    fclose(fp3);

    return 0;
}


This code does not handle errors.
Also, more than 19 bytes of lines have unintended consequences.

If you can fully use C++, please refer to Sayuri's answer.There is no limit to the length of the line, and you can feel safe in the event of an error.


2022-09-30 20:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.