目前我能够(我认为)使用 fopen 打开一个文件。出于测试目的,我希望能够将文件的内容传递到输出文件,但我没有得到想要的结果。这是一些代码:
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[]){ //practice on utilizing IO
char filepath[100];
char filepath2[100];
strcpy(filepath,"./");
strcpy(filepath,"./");
char typed[90];
char msg[1024];
FILE * new_file;
FILE * old_file;
// printf("Input file to be created\n");
printf("File to be opened as input: \n");
printf("--->");
fgets(typed,90,stdin); //read in file name
strtok(typed, "\n");
strcat(filepath,typed);
old_file = fopen(filepath, "r");
printf("file to output to: \n");
fgets(filepath2,100, stdin);
strtok(filepath2, "\n");
///attempt to create that file
new_file = fopen(filepath2,"w");
//printf("%s\n", msg);
}
感谢任何帮助。
最佳答案
在程序中打开文件句柄与在文字处理器中打开文档略有不同。这更像是打开一本书。要阅读或书写,您必须使用眼睛(消费数据)或铅笔(产生数据)。
由于您打开了文件,因此需要从第一个文件读取数据并将其写入第二个文件。像这样的东西:
size_t nread;
do {
nread = fread(msg, 1, 1024, old_file);
fwrite(msg, 1, nread, new_file);
} while(nread != 0);
或者
int nread;
do {
nread = fgets(msg, 1023, old_file);
fputs(msg, new_file);
} while (nread > 0);
或者甚至一次只是一个字符。
int c;
while ( (c=fgetc(old_file)) != EOF) {
fputc(c, new_file);
}
此外,您没有在第二个文件前添加“./”。不确定这是否重要,但您对第一个文件执行了此操作。
此外,您应该在 new_file 上使用 fopen
。 freopen
本身不是错误,但它很奇怪并且会让其他人(包括我)感到困惑。
The freopen() function opens the file whose name is the string pointed to by path and associates the stream pointed to by stream with it. The original stream (if it exists) is closed. The mode argument is used just as in the fopen() function. src:manpage
因此,它会按照您的意愿打开流,但在执行此操作时会破坏标准输出。所以你的程序不能再正常输出了。这可能并不重要,但似乎也没有任何真正的优势。
关于c - 将输入文件传递给 C 中的输出文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16228201/