c语言写入文件方法是什么?

c语言写入文件方法是什么?,第1张

程序注意的一点,二进制和文本形式的读取区别你需要巩固,读的文件就不要以读写形式打开,养成一个好的习惯。\x0d\x0a另外一个不太重要的一点,id确实很少作为int类型的,因为有些id会很长,比如10位20位,这样int就存不下了,而用char数组存的话只需要10个字节20个字节就能存下,对于每一位也好比较。\x0d\x0a#include \x0d\x0a#include \x0d\x0atypedef struct student\x0d\x0a{\x0d\x0a int unsigned id\x0d\x0a float score [3]\x0d\x0a float rank\x0d\x0a}Student\x0d\x0a\x0d\x0aint main ()\x0d\x0a{\x0d\x0a Student s\x0d\x0a FILE * fp\x0d\x0a fp=fopen("C:\\f11.txt","r")//尽量以可读方式打开\x0d\x0a if (!fp)\x0d\x0a {\x0d\x0a printf("file cannot be opened")\x0d\x0a exit(1)\x0d\x0a }\x0d\x0a //fscanf(fp,"%d %f %f %f",&s.id,&s.score[0],&s.score[1],&s.score[2])这一行拿到下面while语句里面\x0d\x0a //fprintf(stdout,"%g",s.score[2]) \x0d\x0a FILE * fw\x0d\x0a fw=fopen("C:\\f11a.txt","w")//注意wb是以2进制形式打开文件,还有目录的格式\x0d\x0a if (!fw)\x0d\x0a {\x0d\x0a printf("file cannot be opened")\x0d\x0a exit(1)\x0d\x0a } \x0d\x0a\x0d\x0a while(!feof(fp))\x0d\x0a {\x0d\x0a fscanf(fp,"%03d%f%f%f",&s.id,&s.score[0],&s.score[1],&s.score[2])\x0d\x0a s.rank=(s.score[0]+s.score[1]+s.score[2])/3\x0d\x0a fprintf(fw,"%03d\t%.1f\t%.1f\t%.1f\t%.1f\n", s.id, s.score[0], s.score[1], s.score[2], s.rank)//尤其注意fprintf和fwrite不同,fwrite是以二进制形式写文件,如果用fwrite的话将会显示乱码,fwrite和fread配套,fscanf和fprintf配套\x0d\x0a }\x0d\x0a\x0d\x0a fclose (fp)\x0d\x0a fclose(fw)\x0d\x0a return 0\x0d\x0a}

C++的文本文件写入

// outfile.cpp -- writing to a file

#include <iostream>

#include <fstream>// for file I/O

int main()

{

using namespace std

char automobile[50]

int year

double a_price

double d_price

ofstream outFile // create object for output

outFile.open("carinfo.txt") // associate with a file

cout <<"Enter the make and model of automobile: "

cin.getline(automobile, 50)

cout <<"Enter the model year: "

cin >>year

cout <<"Enter the original asking price: "

cin >>a_price

d_price = 0.913 * a_price

// display information on screen with cout

cout <<fixed

cout.precision(2)

cout.setf(ios_base::showpoint)

cout <<"Make and model: " <<automobile <<endl

cout <<"Year: " <<year <<endl

cout <<"Was asking $" <<a_price <<endl

cout <<"Now asking $" <<d_price <<endl

// now do exact same things using outFile instead of cout

outFile <<fixed

outFile.precision(2)

outFile.setf(ios_base::showpoint)

outFile <<"Make and model: " <<automobile <<endl

outFile <<"Year: " <<year <<endl

outFile <<"Was asking $" <<a_price <<endl

outFile <<"Now asking $" <<d_price <<endl

outFile.close() // done with file

return 0

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/11617791.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-17
下一篇 2023-05-17

发表评论

登录后才能评论

评论列表(0条)

保存