Write to .txt file?

Stian Olsen picture Stian Olsen · Jul 20, 2012 · Viewed 593.5k times · Source

How can I write a little piece of text into a .txt file? I've been Googling for over 3-4 hours, but can't find out how to do it.

fwrite(); has so many arguments, and I don't know how to use it.

What's the easiest function to use when you only want to write a name and a few numbers to a .txt file?

Edit: Added a piece of my code.

    char name;
    int  number;
    FILE *f;
    f = fopen("contacts.pcl", "a");

    printf("\nNew contact name: ");
    scanf("%s", &name);
    printf("New contact number: ");
    scanf("%i", &number);


    fprintf(f, "%c\n[ %d ]\n\n", name, number);
    fclose(f);

Answer

user529758 picture user529758 · Jul 20, 2012
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
    printf("Error opening file!\n");
    exit(1);
}

/* print some text */
const char *text = "Write this to the file";
fprintf(f, "Some text: %s\n", text);

/* print integers and floats */
int i = 1;
float py = 3.1415927;
fprintf(f, "Integer: %d, float: %f\n", i, py);

/* printing single chatacters */
char c = 'A';
fprintf(f, "A character: %c\n", c);

fclose(f);