'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!
Solution 1:[1]
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");
...
Solution 2:[2]
#include <stdio.h>
#define FILE_NAME "text.txt"
int main()
{
FILE* file_ptr = fopen(FILE_NAME, "w");
fclose(file_ptr);
return 0;
}
Solution 3:[3]
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"));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | sschrass |
Solution 3 | Epic Speedy |