Click here to Skip to main content
15,891,409 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
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 for fprint command is

C
#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 for fsanf is

C
int t_size; 

FILE * fp;	
fp = fopen ("xxx.txt", "r"); 
fscanf(fp, "%d", &t_size); 
fclose(fp);
Posted
Updated 16-Nov-14 1:15am
v4
Comments
[no name] 16-Nov-14 6:12am    
Your first file is: FILE *fp;
Think about to open a second file. For this you need to declare a second file hanlde, e.g.:

FILE *fp_write;
fp_write= fopen(...);
[no name] 16-Nov-14 6:26am    
I tried it but din't worked
[no name] 16-Nov-14 6:27am    
What does not work? Have a look to the two Solutions, there you will find all what you need.
[no name] 16-Nov-14 6:34am    
the solutions work but no in my program. I update the code add the program!
[no name] 16-Nov-14 6:37am    
What means "it does not work"? Any error message? Or the result is not what you expect?

Please be more specific.

not sure what your issue is - you could do this (separate file handle for reading and writing) :-

C++
#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 :-

C++
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
 
Share this answer
 
Easy! Just create a second FILE instance:
C++
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!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900