0

假设我有一个名为 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

4 回答 4

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

注意:来源有一个小错误,我在此处修复。

于 2013-06-26T16:08:50.177 回答
1

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

于 2013-06-26T16:07:02.200 回答
0

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

于 2013-06-26T16:08:51.700 回答
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);
}
于 2013-06-26T16:13:37.443 回答