Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
99 views
in Technique[技术] by (71.8m points)

c - Write to .txt file?

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("
New contact name: ");
scanf("%s", &name);
printf("New contact number: ");
scanf("%i", &number);

fprintf(f, "%c
[ %d ]

", name, number);
fclose(f);
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
    printf("Error opening file!
");
    exit(1);
}

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

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

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

fclose(f);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...