173

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);
Neuron
  • 5,141
  • 5
  • 38
  • 59
Stian Olsen
  • 1,939
  • 3
  • 13
  • 9
  • @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 Jul 20 '12 at 11:48

3 Answers3

310
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 characters */
char c = 'A';
fprintf(f, "A character: %c\n", c);

fclose(f);
endolith
  • 25,479
  • 34
  • 128
  • 192
23
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);
cppcoder
  • 22,227
  • 6
  • 56
  • 81
-10

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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jeeva
  • 4,585
  • 2
  • 32
  • 56
  • 3
    That's hard work compared to using `fprintf()` or `fputs()`. Especially `fprintf()` since a few numbers must be written too. – Jonathan Leffler Jul 20 '12 at 06:38
  • 9
    And `"c:\\test.txt"` is an unlikely file name; the question is tagged [tag:linux]. – Keith Thompson Jul 20 '12 at 06:45
  • 17
    -1 The OP asked for the easiest function to use. And to write text, but you're opening the file in binary mode. And it's poor practice to fail to report an open error. – Jim Balter Jul 20 '12 at 06:54