Reputation: 739
So, I have this code:
#include <stdio.h>
int main(int argc, char *argv[]){
FILE *ReadFile, *WriteFile;
float key;
int quantKeys,T;
int i;
/* errors verification */
if (argc < 3){
printf(" Use the correct entry parameters.\n");
exit(1);
}
if((ReadFile = fopen(argv[1],"rw")) == NULL){
printf("Error when trying to open the file\n");
exit(1);
}
if((WriteFile = fopen(argv[2],"rw")) == NULL){
printf("Error when trying to open the file.\n");
exit(1);
}
/* main code */
quantKeys = 45658;
T = 5;
fprintf(WriteFile,"%d",T);
fprintf(WriteFile,"%d",quantKeys);
fclose(ReadFile);
fclose(WriteFile);
return 0;
}
All I want to do is write the variables "quantChaves" and "T" in a text file, that I pass as the third parameter of the main function. It compiles and runs with no problems, but my text file keeps empty after I run it. What I am doing wrong?
Upvotes: 1
Views: 127
Reputation: 464
If you want to write in a file you should use
w
: Create an empty file w+
: Create an empty file and open it for update r+
: Open a file for update a+
: Open a file for update with all output operations writing data at the end of the fileUpvotes: 1
Reputation: 4218
rw
isn't a valid mode for fopen
. If you want to write, you can use w
, w+
, r+
, or a+
. Full details are in your man
pages, or here.
The gist of the differences:
w
doesn't allow reading
r+
doesn't create a new file if it doesn't exist
a+
appends the text instead of overwriting the file contents.
Upvotes: 6