C语言 向文件中写入字符串

wangk1230 2011-10-13 10:25:55
非常基本非常简单的问题……可是本人实在太菜了……求指导

求已知长方形的面积(a=3,b=4,s=a*b)
然后在同目录下的answer.txt文件中写入如下一行文本:
The answer is ***.
其中的***是计算出的结果。

请问改如何写将这行文本写入文件的代码?希望各位达人不吝赐教,非常感谢!!
...全文
1406 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
wangk1230 2011-10-17
  • 打赏
  • 举报
回复
谢谢大家的帮助!问题解决了!
Linux-Torvalds 2011-10-16
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <stdlib.h>

int main()
{
int a = 3;
int b = 4;
FILE* fp;

if ((fp=fopen("answer.txt", "w+")) == NULL) {
printf("file open error.\n");
abort();
}
fprintf(fp, "The answer is %d.\n", a*b);
fclose(fp);
return 0;
}
fengzhiquxiang1 2011-10-16
  • 打赏
  • 举报
回复
師傅可以幫徒弟擦屁股[Quote=引用 7 楼 shaoxiaojing5193 的回复:]

引用 6 楼 zhao4zhong1 的回复:

请牢记:师傅是不能代替徒弟上厕所的。


顶!!!!!!!
[/Quote]
wangk1230 2011-10-16
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 zhao4zhong1 的回复:]
请牢记:师傅是不能代替徒弟上厕所的。
[/Quote]
师傅~徒弟走了十条街还木有厕所快要憋死了哇~走投无路所以求救哇~
chen_af 2011-10-14
  • 打赏
  • 举报
回复
唉,现在的娃阿,都不自己动手阿,这么简单的还要等别人给答案阿。
chen_af 2011-10-14
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc,char **argv)
{
char file[255+1];

FILE *fp;

memset(file,0x0,sizeof(file));
sprintf(file,"/home/xxx/answer.txt");

if((fp=fopen(file,"a"))==NULL)
{
printf("open file=[%s] error\n",file);
exit(-1);
}

fprintf(fp,"The answer is %d.\n",3*4);

fflush(fp);
fclose(fp);
}
赵4老师 2011-10-14
  • 打赏
  • 举报
回复
请牢记:师傅是不能代替徒弟上厕所的。
赵4老师 2011-10-14
  • 打赏
  • 举报
回复
#include <stdio.h>
void main() {
int a,b,s;
FILE *p;

a=3;b=4;
s=a*b;
p=fopen("answer.txt","w");
fprintf(p,"The answer is %d.",s);
fclose(p);
}
pathuang68 2011-10-14
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 c_losed 的回复:]

C/C++ code
FILE *p = fopen("d:\\1.txt","w+");

char buf[] = "The answer is ***.";

fwrite(buf, strlen(buf),1, p );

fclose(p);
[/Quote]

++
qq120848369 2011-10-14
  • 打赏
  • 举报
回复
fputs("Hello");
fprintf("Hello\n");
shaoxiaojing5193 2011-10-14
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 zhao4zhong1 的回复:]

请牢记:师傅是不能代替徒弟上厕所的。
[/Quote]

顶!!!!!!!
自信男孩 2011-10-13
  • 打赏
  • 举报
回复
恩,首先呢,你需要打开一个文件,以可写方式打开。
然后,把"The answer is"存入一个字符数组中(比如,char str[] = "The answer is";),定义一个变量s用于存储得到的长方形的面积。
最后,你可以尝试一下使用fprintf()函数。fprintf(fp, "%s %d\n", str, s);关闭文件。
c_losed 2011-10-13
  • 打赏
  • 举报
回复
FILE *p = fopen("d:\\1.txt","w+");

char buf[] = "The answer is ***.";

fwrite(buf, strlen(buf),1, p );

fclose(p);

70,035

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧