5

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!

Hassen Fatima
  • 401
  • 3
  • 7
  • 12
  • 4
    `a` is for "append". if the file exists, it'll be appended to. you probably want `w`, for write - if the file exists, it'll be truncated and you start fresh. – Marc B Nov 30 '15 at 21:22
  • Marc is correct, also be sure to close at the end if you don't want unpredictable behaviour. – ForeverStudent Nov 30 '15 at 21:23
  • fopen creates the file if you open a new file for writing see for example: http://stackoverflow.com/questions/9840629/create-a-file-if-one-doesnt-exist-c – terence hill Nov 30 '15 at 21:23
  • You could not find the internet? – Jongware Nov 30 '15 at 21:48

3 Answers3

12
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");
...
Ishamael
  • 12,583
  • 4
  • 34
  • 52
  • 1
    (You should check that `fp != NULL`, but you already do) ; Don't forget to call `fclose(fp);` at end. You might want to sometimes call `fflush` – Basile Starynkevitch Nov 30 '15 at 21:23
  • The "at" mode for `fopen()` is not part of **7.21.5.3 The `fopen` function** in the C standard. http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf – Andrew Henle Nov 30 '15 at 21:27
  • What does the fprintf(fp, "change case \n"); do? Thanks – Hassen Fatima Nov 30 '15 at 21:27
  • 2
    @HassenFatima, it writes "change case" into a file that handle `fp` points to. Unlike regular `printf`, that writes into stdout. – Ishamael Nov 30 '15 at 21:28
3
#include <stdio.h>
#define FILE_NAME "text.txt"

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

    return 0;
}
sschrass
  • 7,014
  • 6
  • 43
  • 62
Dostonbek Oripjonov
  • 1,508
  • 1
  • 12
  • 28
1

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"));
Epic Speedy
  • 636
  • 1
  • 11
  • 25