在C中用一个编译2个文件命令 [英] Compile 2 file commands in one in C
问题描述
您好我正在研究C中的项目。我想首先打开一个名为op.txt的文件,使用fcanf读取它的第一个数字并将num放入int中。然后我想使用另一个命令将该num写入另一个名为o.txt的文件中
但是如何在main函数中使用第二个File命令使用第一个文件的fopen?
fprint
命令的代码是
#include < stdio.h >
main()
{
FILE * fp;
int a = 1 ;
fp = fopen( test.txt, w +);
fprintf(fp, int是%d \ n,a);
fclose(fp);
}
和 fsanf
是
int t_size;
FILE * fp;
fp = fopen( xxx.txt, r);
fscanf(fp, %d,& t_size);
fclose(fp);
不确定你的问题是什么 - 你可以这样做(单独的文件句柄用于阅读和写作): -
#include < stdio.h >
main()
{
int t_size;
FILE * fp_read;
fp_read = fopen( xxx.txt, r);
fscanf(fp_read, %d,& t_size);
fclose(fp_read);
FILE * fp_write;
int a = 1 跨度>;
fp_write = fopen( test.txt, w +);
fprintf(fp_write, int是%d \ n,a);
fclose(fp_write);
}
使您的代码更容易阅读 - 或者您只需关闭然后重新使用文件句柄: -
main()
{
FILE * fp;
int t_size;
fp = fopen( xxx.txt, r);
fscanf(fp, %d,& t_size);
fclose(fp);
int a = 1 ;
fp = fopen( test.txt, w +);
fprintf(fp, int是%d \ n,a);
fclose(fp);
}
顺便说一下,你的代码中没有显示处理文件结束/错误条件< /块引用>
轻松!只需创建第二个FILE实例:
FILE * fpInput;
FILE * fpOutput;
fpInput = fopen( xxx.txt, r);
fscanf(fpInput, %d,& t_size);
fpOutput = fopen( yyy.txt, w +);
fprintf(fpOutput, int为%d \ n,t_size);
fclose(fpInput);
fclose(fpOutput);
并且请:删除问题被认为是粗鲁的 - 这对其他人没有帮助类似的问题!
Hi I'm working on a project in C. I want first to open a file called op.txt read the first num of it using fcanf and put the num into a int. Then I want to use another command to write that num into a different file called o.txt
But How can I use a second File command inside the main function which I use the fopen of the first file?
The code forfprint
command is
#include <stdio.h> main() { FILE *fp; int a = 1; fp = fopen("test.txt", "w+"); fprintf(fp, "The int is %d\n", a); fclose(fp); }
and forfsanf
is
int t_size; FILE * fp; fp = fopen ("xxx.txt", "r"); fscanf(fp, "%d", &t_size); fclose(fp);解决方案not sure what your issue is - you could do this (separate file handle for reading and writing) :-
#include <stdio.h> main() { int t_size; FILE *fp_read; fp_read = fopen ("xxx.txt", "r"); fscanf(fp_read, "%d", &t_size); fclose(fp_read); FILE *fp_write; int a = 1; fp_write = fopen("test.txt", "w+"); fprintf(fp_write, "The int is %d\n", a); fclose(fp_write); }
that makes your code slightly easier to read - or you could simply close and then re-use the file handle :-
main() { FILE *fp; int t_size; fp = fopen ("xxx.txt", "r"); fscanf(fp, "%d", &t_size); fclose(fp); int a = 1; fp = fopen("test.txt", "w+"); fprintf(fp, "The int is %d\n", a); fclose(fp); }
btw, no-where in your code do you show handling for end-of-file / error conditions
Easy! Just create a second FILE instance:
FILE* fpInput; FILE* fpOutput; fpInput = fopen ("xxx.txt", "r"); fscanf(fpInput, "%d", &t_size); fpOutput = fopen ("yyy.txt", "w+"); fprintf(fpOutput, "The int is %d\n", t_size); fclose(fpInput); fclose(fpOutput);
And please: it's considered rude to remove questions - it doesn't help others with a similar problem!
这篇关于在C中用一个编译2个文件命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!