简体   繁体   中英

What do I need to do to read a file then pick a line and write it to another file (Using C)?

I've been trying to figure out how I would, read a.txt file, and pick a line of said file from random then write the result to a different.txt file for example: .txt bark run car take line 2 and 3 add them together and write it to Result.txt on a new line. How would I go about doing this???

I've tried looking around for resources for fopen(), fgets(), fgetc(), fprintf(), puts(). Haven't found anything so far on reading a line that isn't the first line, my best guess: -read file -print line of file in memory IE an array -pick a number from random IE rand() -use random number to pick a array location -write array cell to new file -repeat twice -make newline repeat task 4-6 -when done -close read file -close write file

Might be over thinking it or just don't know what the operation to get a single line anywhere in a file is. just having a hard time rapping my head around it.

I'm not going to solve the whole exercise, but I will give you a hint on how to copy a line from one file to another. You can use fgets and increment a counter each time you find a line break, if the line number is the one you want to copy, you simply dump the buffer obtained with fgets to the target file with fputs .

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

int main(void)
{
    // I omit the fopen check for brevity
    FILE *in = fopen("demo.c", "r");
    FILE *out = fopen("out.txt", "w");

    int ln = 1, at = 4; // copy line 4
    char str[128];

    while (fgets(str, sizeof str, in))
    {
        if (ln == at)
        {
            fputs(str, out);
        }
        if (strchr(str, '\n') && (ln++ == at))
        {
            break;
        }
    }
    fclose(in);
    fclose(out);
    return 0;
}

Output:

int main(void)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM