Benjamin
Benjamin

Reputation: 561

Writing to a file within a folder in C

How can I do this?

I know opening a new file is something akin to this:

    fpcon=fopen("konf_in","w");
    printf("Whatever I want to input");
    fclose(fpcon);

The output file only needs to be a simple .txt or .dat file

Upvotes: 0

Views: 1303

Answers (1)

João Pinho
João Pinho

Reputation: 3775

To write to a file, you need to call fprintf and pass your file pointer which is fpcon, see this example:

char name[20];
int  number;

FILE *f;
f = fopen("/your_folder/sample.txt", "w");

if (f == NULL) {
    printf("Error opening file!\n");
    exit(1);
}

printf("\nNew contact name (max 19): ");
fgets(name, sizeof(name), stdin);

printf("New contact number: ");
scanf("%d", &number);    

fprintf(f, "%s - %d\n", name, number);
fclose(f);

This page gives you further intel on how to handle file writes, appends, etc.

Just for clarification, the allowed modes for fopen are as follows:

  • r - open for reading
  • w - open for writing (file need not exist)
  • a - open for appending (file need not exist)
  • r+ - open for reading and writing, start at beginning
  • w+ - open for reading and writing (overwrite file)
  • a+ - open for reading and writing (append if file exists)

Upvotes: 2

Related Questions