繁体   English   中英

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

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

假设我有一个名为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语言的新手,在弄清楚这一点时遇到了一些麻烦。 很感谢任何形式的帮助。

这是一个例子:

#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

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

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

有用的电话: 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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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