
第一种:
#include <stdioh>#include <stringh>
#include <stdlibh>
struct student //结构体
{
char name[20]; //姓名
int english; //英语
int math; //数学
int program; //程序设计
}s[50];
void daoru(struct student s[], int n) //文件导入函数
{
FILE p;
int i=n;
if((p=fopen("studentstxt", "r"))==NULL)
{
printf("无法打开此文件!");
}
else
{
while(!feof(p))
{
fscanf(p, "%s%d%d%d", s[i]name, &s[i]english, &s[i]math, &s[i]program);
i++;
n=n+1;
}
}
fclose(p);
}
void paixu(struct student s[], int n) //排序函数
{
int i, j;
struct student stu;
int allscore[2];
for (i=0; i<n-1; i++)
{
for (j=i+1; j<n; j++)
{
allscore[0]=s[i]english+s[i]math+s[i]program;
allscore[1]=s[j]english+s[j]math+s[j]program;
if (allscore[0]<allscore[1])
{
stu=s[i];
s[i]=s[j];
s[j]=stu;
}
}
}
}
void dayin(struct student s[], int n) //显示所有信息
{
int i;
printf("\n姓名\t英语\t数学\t程序设计\t总分\n");
for (i=0; i<n; i++)
{
printf("%s\t%d\t%d\t%d\t\t%d\n",s[i]name, s[i]english, s[i]math, s[i]program, (s[i]english+s[i]math+s[i]program));
}
}
int main() //主函数
{
int k, n=0;
daoru(s, &n);
paixu(s, n);
dayin(s, n);
return 0;
}
输出结果:
第二种二进制的导入也差不多,这里就不写了
通常以text保存(streamWriter),任何系统都可以调用,文件后缀可以自行保存为“ini/dat”等等,但是调用数据需要逐行string分析,从而实现数据库的基本使用性。
给你个小例子:
using SystemIO;
private static string getConnDetail(string parameter)//gets the connection details from txt file
{
try
{
string filename = "conntxt";
using (StreamReader sr = new StreamReader(filename))
{
string line;
while ((line = srReadLine()) != null)
{
//do stuff
string[] subs = lineSplit(':');
if (subs[0] == parameter)
{
srClose();
return subs[1];
}
}
srClose();
return "fail";
}
}
catch (Exception ex)
{
return exMessage;
}
}
然后在同一路径下创建一个txt文件命名conntxt,内容:
Server:YourComputerName\SQLEXPRESS
DB:YourDBName
User:sa
Pass:pass
最后你如果想察看servername,就调用getConnDetail(“Server”)
返回string: "YourComputerName\SQLEXPRESS"
这个例子是从txt读取数据,如果要写入数据,参考3楼的连接。也可以直接用openfile(filepath/filename,opentype)指令打开文件然后写入或者读取。 具体可以查找关键词:FileOpenText ,主要阅读与File指令相关。
//maincpp
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cstdlib>
using namespace std;
//产生随机IP地址
string RandIP()
{
stringstream ss;
for (int i=0; i<4; ++i)
{
ss << (rand()%256);
if (i<3)
ss << '';
}
return ssstr();
}
//写IP地址到文件filename中
void WriteIP(const string& filename)
{
ofstream fout(filenamec_str());
fout << RandIP();
}
//从文件filename中读取IP地址
unsigned long ReadIP(const string& filename)
{
ifstream fin(filenamec_str());
int val=0;
char ch=0;
unsigned long ip_val=0;
for (int i=0; i<4; ++i)
{
fin >> val >> ch;
ip_val = (ip_val<<8) + val;
}
return ip_val;
}
int main()
{
string filename("iptxt");
WriteIP(filename);
unsigned long ip_val=ReadIP(filename);
cout << ip_val << endl;
return 0;
}
读写文件路径 filePath 需要使用 wxenvUSER_DATA_PATH + '/tmptxt' 才可以读写成功。
坑:无论怎么读,返回的类型都是String类型,不会出现ArrayBuffer类型。
以上就是关于用C语言编写 文件读写全部的内容,包括:用C语言编写 文件读写、C# 请问开发的小程序中的数据 怎样保存并在此调用保存内容、c++小程序 随机产生ip地址写入一个文件 然后读取 转换成16进制 求帮助等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)