Reputation: 387
I know this is how you read from a file. I also want to print my output to the same name of the file plus ".txt". So if my file is called "text" I want to print it to a file called "text.txt".
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(int argc, char* argv[1])
{
FILE* Data2;
Data2 = fopen(argv[1], "r");
if (Data2 == NULL)
{
printf("ERROR");
exit(100);
}
return 0;
}
Would it be something like this? Is it better to use "a" or "w" in the fopen? I want to write to it several times.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(int argc, char* argv[1])
{
FILE* Data2;
FILE* Data3;
Data2 = fopen(argv[1], "r");
Data3 = fopen(argv[1].txt, "a");
if (Data2 == NULL)
{
printf("ERROR");
exit(100);
}
fprintf(Data3, "\n Print something \n");
fprintf(Data3, "\n Print something \n");
fprintf(Data3, "\n Print something \n");
return 0;
}
Upvotes: 1
Views: 78
Reputation: 21435
argv[1]
is a string. The .txt
syntax doesn't mean appending ".txt"
to it.
However, you can do that by creating a new buffer with enough size (computed using strlen
) and pasting both strings in there
char *fname = calloc(strlen(argv[1]) + 5, sizeof(fname[0])); /* +5 to have space for .txt and terminator */
strcpy(fname, argv[1]);
strcat(fname, ".txt");
Data3 = fopen(fname, "a");
Or, you could use asprintf
if you can and want to use GNU extensions instead of POSIX standard:
char *fname = NULL;
asprintf(&fname, "%s.txt", argv[1]);
Data3 = fopen(fname, "a");
Now, regarding the opening of the file, it is important concerning the moment you issue the fopen
call: if you pass in "a"
then the contents before the opening of the file will remain there. If you pass in "w"
then said contents will be removed. In both cases you are able to write multiple things into the file.
Upvotes: 2