159
votes

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?

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);
3
@user1054396: The problem isn't with the printing (which you got right), but with the reading via scanf. If you read %s, you must read into a buffer of sufficient length, not a single char. - Kerrek SB
"fwrite() has so many arguments'" come off it. It has four. - user207421

3 Answers

289
votes
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 pi= 3.1415927;
fprintf(f, "Integer: %d, float: %f\n", i, pi);

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

fclose(f);
22
votes
FILE *fp;
char* str = "string";
int x = 10;

fp=fopen("test.txt", "w");
if(fp == NULL)
    exit(-1);
fprintf(fp, "This is a string which is written to a file\n");
fprintf(fp, "The string has %d words and keyword %s\n", x, str);
fclose(fp);
-4
votes

Well, you need to first get a good book on C and understand the language.

FILE *fp;
fp = fopen("c:\\test.txt", "wb");
if(fp == null)
   return;
char x[10]="ABCDEFGHIJ";
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);
fclose(fp);