Hassen Fatima
Hassen Fatima

Reputation: 423

How to create a new text file in C?

I am creating a program which reads data from one text file and changes it size to upper or lower case and then stores that data in a new file. I have searched the internet, but I can't find how to create a new text file.

#include <stdio.h>
int main(void) {

        FILE *fp = NULL;

        fp = fopen("textFile.txt" ,"a");

        char choice;

        if (fp != NULL) {

                printf("Change Case \n");
                printf("============\n");
                printf("Case (U for upper, L for lower) : ");
                scanf(" %c", &choice);
                printf("Name of the original file : textFile.txt \n");
                printf("Name of the updated file : newFile.txt \n");

I know this is incomplete, but I can't figure out how to crate a new text file!

Upvotes: 6

Views: 90102

Answers (3)

Epic Speedy
Epic Speedy

Reputation: 729

Find it quite strange there isn't a system call API for explicitly creating a new file. A concise version of the above answers is:

fclose(fopen("text.txt", "a"));

Upvotes: 0

Dostonbek Oripjonov
Dostonbek Oripjonov

Reputation: 1674

#include <stdio.h>
#define FILE_NAME "text.txt"

int main()
{
    FILE* file_ptr = fopen(FILE_NAME, "w");
    fclose(file_ptr);

    return 0;
}

Upvotes: 5

Ishamael
Ishamael

Reputation: 12795

fp = fopen("textFile.txt" ,"a");

This is a correct way to create a text file. The issue is with your printf statements. What you want instead is:

fprintf(fp, "Change Case \n");
...

Upvotes: 12

Related Questions