![](/img/trans.png)
[英]C program: How to read from one file and write into another? Indexing
[英]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
注意:來源有一個小錯誤,我在這里已修復。
看看: http : //www.cs.toronto.edu/~yuana/ta/csc209/binary-test.c正是您想要做的
如果要將整個內容從一個文件復制到另一個文件,則可以逐字節讀取文件並寫入其他文件。 這可以用getc()和putc()完成。 如果要通過復制整行來做到這一點,則應制作一個具有一定長度的char buffer [],然后使用gets()從文件中讀取char並將其存儲到緩沖區。 所有功能都有與文件一起使用的版本。 我的意思是fgetc(),fgetc()fgets()在哪里。 有關更多詳細信息,您可以在Google中搜索完整的說明。
//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.