C:如何从一个文件中读取一行,并将其附加到另一个文件中?

时间:2013-06-26 16:03:36

标签: c

假设我有一个名为greeting.txt的文件,其中包含以下内容:

Hello
World
How
Are
You

如何读取每一行,然后将其附加到C中的另一个文件?到目前为止,我有这个:

#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;
}

预期的结果是会有一个名为greeting2.txt的文件,其内容与greeting.txt完全相同。

我的计划是使用WHILE循环遍历greeting.txt的每一行并将每一行附加到greeting2.txt,但我不太确定如何读取该行,然后写入。

我是C的新手,我在解决这个问题时遇到了一些麻烦。非常感谢任何帮助。

4 个答案:

答案 0 :(得分:2)

以下是一个例子:

#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;
}

来源:

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

注意:源有一个小错误,我在这里修复了。

答案 1 :(得分:1)

看看: http://www.cs.toronto.edu/~yuana/ta/csc209/binary-test.c 这正是你想做的事情

答案 2 :(得分:0)

如果要将整个内容从一个文件复制到另一个文件,则可以逐字节读取文件并写入其他文件。这可以使用getc()和putc()来完成。如果你想通过复制整行来实现它,你应该创建一个具有一定长度的char buffer [],然后使用gets()从文件中读取char并将其存储到缓冲区。所有功能都有适用于文件的版本。我的意思是fgetc(),fgetc()fgets()在哪里。有关详细信息,您可以在谷歌搜索完整的描述。

答案 3 :(得分:0)

有用的来电:freadfseekfwrite

//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);
}
相关问题