简体   繁体   中英

C: How to read a line from one file, and append it to another?

Suppose I have a file called greeting.txt that has the following contents:

Hello
World
How
Are
You

How do I read each line and then append it to another file in C? So far, I have this:

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

int main()
{
    FILE *infile;
    FILE *outfile;

    infile = fopen("greeting.txt", "r");
    outfile = fopen("greeting2.txt", "w");

    //Trying to figure out how to do the rest of the code

    return 0;
}

The expected result is that there will be a file named greeting2.txt with the exact same contents as greeting.txt.

My plan is to use a WHILE loop to cycle through each line of greeting.txt and appending each line to greeting2.txt, but I'm not quite sure how to read the line, then write.

I'm new to C, and I'm having some trouble figuring this out. Any help is very much appreciated.

Here's an example:

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

#define MAX 512

int main(int argc, char *argv[])
{
  FILE *file, *file2;
  char line[MAX];

  if (argc != 4)
  {
    printf("You must enter: ./replace old-string new-string file-name\n")
    exit(1);
  }

  //Here's what you're interested in starts....
  file = fopen(argv[3], "r");
  file2 = fopen("temp", "w");
  while (fgets(line,sizeof(line),file) != NULL);
  {
    /*Write the line */
    fputs(line, file2);
    printf(line);

  }
  fclose (file);
  fclose (file2);
  //Here is where it ends....

  return 0;
}

Source:

http://cboard.cprogramming.com/c-programming/82955-c-reading-one-file-write-another-problem.html

Note: The source has one small error which I fixed here.

If you want to copy the entire content from one file to other then you can read file byte by byte and write to other. This could be done with getc() and putc(). If you want to do it by copying entire line you should make a char buffer[] with some length and then use gets() to read char from file and store it to buffer. All functions have versions which works with files. I mean that where is fgetc(), fgetc() fgets(). For futher details you can search full description in google.

Helpful calls: fread , fseek , fwrite

//adjust buffer as appropriate
#define BUFFER_SIZE 1024
char* buffer = malloc(BUFFER_SIZE);//allocate the temp space between reading and writing
fseek(outfile, 0, SEEK_END);//move the write head to the end of the file
size_t bytesRead = 0;
while(bytesRead = fread((void*)buffer, 1, BUFFER_SIZE, infile))//read in as long as there's data
{
    fwrite(buffer, 1, BUFFER_SIZE, outfile);
}

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