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;
}

line 10: No, you can't concantinate C strings like that

char fname[255];
char *ptr;
strcpy(fname,argv[1]);
ptr = strchr(fname,'.'); // truncate extension
if( strcmp(ptr,".txt") == 0)
{
   printf("Error: can't write to the same file as input file\n");
}
if( ptr != NULL)
   *ptr = '\0';
strcat(fname,".txt");
Data3 = fopen(fname,"w");
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.