C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
C#简单读写txt文件的方法

希望本文所述对大家C#程序设计有所帮助。
这篇文章主要介绍了c中的协变与逆变的相关知识在泛型或委托中如果不使用协变或逆变那么泛型类型是一个固定类型而使用协变或逆变的话则泛型类型可以实现多态化需要的朋友可以参考下
C#简单读写 txt文件的方法
本文实例讲述了C#简单读写txt文件的ຫໍສະໝຸດ 法。分享给大家供大家参考,具体如下:
//write txt StringBuilder builder = new StringBuilder(); FileStream fs = new FileStream(saveFileName, FileMode.Create); StreamWriter sw = new StreamWriter(fs, Encoding.Default); for (int i = 0; i < ds.Tables[0].Rows.Count; i++) {
DataRow dr = ds.Tables[0].Rows[i]; builder.AppendLine(dr["netsn"] + "," + dr["imei"]); //产品S/N号 + IMEI号 } sw.Write(builder); sw.Close(); fs.Close(); if (System.IO.File.Exists(saveFileName)) { System.Diagnostics.Process.Start(saveFileName); //保存成功后打开此文件 } //read txt string[] allLines = File.ReadAllLines(filePath);
C 简单读写文本文件 统计文件的行数 读取文件数据到数组

打开一个文件时,将位置移动到文件尾
文件指针位置在 c++中的用法:
ios::beg ios::end ios::cur
当前位置 例子:
文件头 文件尾
file.seekg(0,ios::beg); //让文件指针定位到文件开头
file.seekg(0,ios::end); //让文件指针定位到文件末尾 file.seekg(10,ios::cur); //让文件指针从当前位置向文件末方向移动 10 个字节 file.seekg(-10,ios::cur); //让文件指针从当前位置向文件开始方向移动 10 个字节 file.seekg(10,ios::beg); //让文件指针定位到离文件开头 10 个字节的位置
很显然,根据以上程序,利用循环,可以逐行读取整个文件内容。
三、统计文件的行数
#include <iostream> #include <fstream> using namespace std;
int CountLines(char *filename) { ifstream ReadFile; int n=0; char line[512]; ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件 if(ReadFile.fail())//文件打开失败:返回 0 {
逐个字符的读取文件: #include <iostream> #include <fstream> using namespace std; void main() { fstream in; char c; in.open("comn.txt",ios::in); while(!in.eof()) {
用C_读取txt文件的方法

用C#读取txt文件的方法1、使用FileStream读写文件文件头:using System;using System.Collections.Generic;using System.Text;using System.IO;读文件核心代码:byte[] byData = new byte[100];char[] charData = new char[1000];try{FileStream sFile = new FileStream("文件路径",FileMode.Open);sFile.Seek(55, SeekOrigin.Begin);sFile.Read(byData, 0, 100); //第一个参数是被传进来的字节数组,用以接受FileStream对象中的数据,第2个参数是字节数组中开始写入数据的位置,它通常是0,表示从数组的开端文件中向数组写数据,最后一个参数规定从文件读多少字符.}catch (IOException e){Console.WriteLine("An IO exception has been thrown!");Console.WriteLine(e.ToString());Console.ReadLine();return;}Decoder d = Encoding.UTF8.GetDecoder();d.GetChars(byData, 0, byData.Length, charData, 0);Console.WriteLine(charData);Console.ReadLine();写文件核心代码:FileStream fs = new FileStream(文件路径,FileMode.Create);//获得字节数组byte [] data =new UTF8Encoding().GetBytes(String);//开始写入fs.Write(data,0,data.Length);//清空缓冲区、关闭流fs.Flush();fs.Close();2、使用StreamReader和StreamWriter文件头:using System;using System.Collections.Generic;using System.Text;using System.IO;StreamReader读取文件:StreamReader objReader = new StreamReader(文件路径);string sLine="";ArrayList LineList = new ArrayList();while (sLine != null){sLine = objReader.ReadLine();if (sLine != null&&!sLine.Equals(""))LineList.Add(sLine);}objReader.Close();return LineList;StreamWriter写文件:FileStream fs = new FileStream(文件路径, FileMode.Create);StreamWriter sw = new StreamWriter(fs);//开始写入sw.Write(String);//清空缓冲区sw.Flush();//关闭流sw.Close();fs.Close();用C#读取.txt文件,常用StreamReader sr = new StreamReader("TestFile.txt")///StreamReader sr = new StreamReader("TestFile.txt",Encoding.GetEncoding("GB2312"))///GBKString line;while ((line = sr.ReadLine()) != null){textBox1 .Text +=ii.ToString ()+" -"+line.ToString()+"\r\n";}加入引用:System.IOStreamReader objReader = new StreamReader("c:\\test.txt");System.IO 命名空间中的对象,尤其是System.IO.StreamReader 类。
C语言文件读写基本操作

C语言文件读写基本操作文件读写是C语言中常用的操作之一,使用文件读写可以对外部文件进行数据输入和输出。
本文将介绍C语言中文件读写的基本操作,包括文件的打开、关闭、读取、写入和定位等。
文件的打开和关闭是文件读写的首要步骤。
可以使用标准库中的fopen函数来打开文件,它可以接收文件名和打开方式作为参数,返回一个指向文件的指针。
例如:```cFILE* fp;fp = fopen("file.txt", "r");```上述代码打开了名为file.txt的文本文件,并将文件指针保存在fp 中。
第二个参数r表示以只读方式打开文件。
其他常见的打开方式包括"w"(写入)、"a"(追加)和"b"(二进制)等。
当文件使用完毕后,应使用fclose函数将其关闭,以释放资源。
例如:```cfclose(fp);```在文件打开之后,可以使用fread函数从文件中读取数据,使用fwrite函数将数据写入文件中。
这两个函数分别接收多个参数,包括读写的数据缓冲区、数据项的大小、数据项的个数和文件指针等。
例如:```cchar buffer[100];fread(buffer, sizeof(char), 100, fp);```上述代码从fp指向的文件中读取了100个字符到buffer缓冲区中。
```cfwrite(buffer, sizeof(char), 100, fp);```上述代码将buffer缓冲区中的100个字符写入fp指向的文件中。
除了fread和fwrite函数外,还可以使用fgetc函数逐个字符读取文件中的数据,使用fputc函数逐个字符写入文件中。
这两个函数分别接收文件指针作为参数。
例如:```cchar ch;ch = fgetc(fp);```上述代码从fp指向的文件中读取一个字符并将其保存在变量ch中。
(完整版)C语言统计文件中的字符数、单词数以及总行数

C语言统计文件中的字符数、单词数以及总行数统计文件的字符数、单词数以及总行数,包括:每行的字符数和单词数文件的总字符数、总单词数以及总行数注意:空白字符(空格和tab缩进)不计入字符总数;单词以空格为分隔;不考虑一个单词在两行的情况;限制每行的字符数不能超过1000。
代码如下#include <stdio.h>#include <string.h>int *getCharNum(char *filename, int *totalNum);int main(){char filename[30];// totalNum[0]: 总行数totalNum[1]: 总字符数totalNum[2]: 总单词数int totalNum[3] = {0, 0, 0};printf("Input file name: ");scanf("%s", filename);if(getCharNum(filename, totalNum)){printf("Total: %d lines, %d words, %d chars\n", totalNum[0], totalNum[2], totalNum[1]);}else{printf("Error!\n");}return 0;}/*** 统计文件的字符数、单词数、行数** @param filename 文件名* @param totalNum 文件统计数据** @return 成功返回统计数据,否则返回NULL**/int *getCharNum(char *filename, int *totalNum){FILE *fp; // 指向文件的指针char buffer[1003]; //缓冲区,存储读取到的每行的内容int bufferLen; // 缓冲区中实际存储的内容的长度int i; // 当前读到缓冲区的第i个字符char c; // 读取到的字符int isLastBlank = 0; // 上个字符是否是空格int charNum = 0; // 当前行的字符数int wordNum = 0; // 当前行的单词数if( (fp=fopen(filename, "rb")) == NULL ){perror(filename);return NULL;}printf("line words chars\n");// 每次读取一行数据,保存到buffer,每行最多只能有1000个字符while(fgets(buffer, 1003, fp) != NULL){bufferLen = strlen(buffer);// 遍历缓冲区的内容for(i=0; i<bufferLen; i++){c = buffer[i];if( c==' ' || c=='\t'){ // 遇到空格!isLastBlank && wordNum++; // 如果上个字符不是空格,那么单词数加1isLastBlank = 1;}else if(c!='\n'&&c!='\r'){ // 忽略换行符charNum++; // 如果既不是换行符也不是空格,字符数加1isLastBlank = 0;}}!isLastBlank && wordNum++; // 如果最后一个字符不是空格,那么单词数加1isLastBlank = 1; // 每次换行重置为1// 一行结束,计算总字符数、总单词数、总行数totalNum[0]++; // 总行数totalNum[1] += charNum; // 总字符数totalNum[2] += wordNum; // 总单词数printf("%-7d%-7d%d\n", totalNum[0], wordNum, charNum);// 置零,重新统计下一行charNum = 0;wordNum = 0;}return totalNum;}在D盘下创建文件demo.txt,并输入如下的内容:运行程序,输出结果为:上面的程序,每次从文件中读取一行,放到缓冲区buffer,然后遍历缓冲区,统计当前行的字符和单词数。
VC读写txt文件

C++读写文本文件#include <iostream>#include <fstream>using namespace std;int main(){const char filename[] = "mytext.txt";ofstream o_file;ifstream i_file;string out_text;//写o_file.open(filename);for (int i = 1; i <= 10; i++){o_file << "第" << i << "行\n"; //将内容写入到文本文件中}o_file.close();//读i_file.open(filename);if (i_file.is_open()){while (i_file.good()){i_file >> out_text; //将读取的内容存储到变量out_text中cout << out_text << endl; //在控制台输出读取的内容。
为什么最后一行的内容会出现两次}}elsecout << "打开文件:" << filename << " 时出错!";i_file.close();system("PAUSE");return 0;}为什么总会将最后一行显示两遍?我的循环似乎没错呀。
笔记:C++文件的读取和写入exit(1);// terminate with error}if(!outfile){cout<<"Unable to open otfile";exit(1);// terminate with error}int a,b;int i=0,j=0;int data[6][2];while(! myfile.eof()){myfile.getline(buffer,10);sscanf(buffer,"%d %d",&a,&b);cout<<a<<" "<<b<<endl;data[i][0]=a;data[i][1]=b;i++;}myfile.close();for(int k=0;k<i;k++){outfile<<data[k][0]<<" "<<data[k][1]<<endl;cout<<data[k][0]<<" "<<data[k][1]<<endl; }outfile.close();return 0;}无论读写都要包含<fstream>头文件读:从外部文件中将数据读到程序中来处理对于程序来说,是从外部读入数据,因此定义输入流,即定义输入流对象:ifsteam infile,infile就是输入流对象。
c语言从txt文件中逐行读入数据存到数组中的实现方法 -回复

c语言从txt文件中逐行读入数据存到数组中的实现方法-回复C语言是一种强大而广泛使用的编程语言,它提供了丰富的功能和灵活性。
在许多应用程序中,我们需要从外部文件中读取数据并将其存储在数组中以便进行进一步处理。
本文将介绍如何使用C语言逐行读取txt文件并将数据存储到数组中的实现方法。
在开始之前,我们需要了解一些基本的概念。
首先,txt文件是一种普通文本文件,其中的内容以纯文本形式存储,不包含特殊格式或二进制数据。
其次,数组是一种数据结构,用于存储相同类型的数据元素。
在C 语言中,我们可以使用数组来存储各种类型的数据,例如整数、字符或字符串。
接下来,让我们来看一下逐行读取txt文件并将数据存储到数组中的步骤:步骤1:打开文件在C语言中,我们首先需要使用标准库函数fopen()来打开txt文件。
此函数需要两个参数:文件名和打开模式。
文件名表示要打开的txt文件的路径和名称,而打开模式表示文件的打开方式(例如,读取、写入或追加)。
对于我们的需求,我们将使用打开模式"r"来以只读方式打开txt文件。
下面是打开txt文件并检查是否成功的示例代码:c#include <stdio.h>int main() {FILE *file = fopen("data.txt", "r");if (file == NULL) {printf("无法打开文件!\n");return -1;}代码继续...fclose(file);return 0;}在上面的示例中,我们使用fopen()函数打开了名为"data.txt"的txt文件。
然后,我们检查file指针是否为空,以确定文件是否成功打开。
如果文件打开失败,我们将打印一条错误消息并返回-1。
步骤2:逐行读取文件内容一旦我们成功打开了txt文件,我们就可以使用标准库函数fgets()来逐行读取文件的内容。
C#实现读写文本文件中的数据

C#实现读写⽂本⽂件中的数据【1】⾸先我们定义⼀段假数据,这⾥以⼀个string为例字 static void Main(string[] args){string data = "我的数据要开始存⼊⽂件了,我好开⼼啊!覆盖了吗?好像覆盖了,真的覆盖了";}【2】接着我们将这个数据写⼊.txt⽂件代码如下:/// <summary>/// 保存数据data到⽂件的处理过程;/// </summary>/// <param name="data"></param>public static String SavaProcess(string data) {System.DateTime currentTime = System.DateTime.Now;//获取当前⽇期的前⼀天转换成ToFileTimestring strYMD = currentTime.AddDays(-1).ToString("yyyyMMdd");//按照⽇期建⽴⼀个⽂件名string FileName = "MyFileSend" + strYMD + ".txt";//设置⽬录string CurDir = System.AppDomain.CurrentDomain.BaseDirectory + @"SaveDir";//判断路径是否存在if(!System.IO.Directory.Exists(CurDir)){System.IO.Directory.CreateDirectory(CurDir);}//不存在就创建String FilePath = CurDir + FileName;//⽂件覆盖⽅式添加内容System.IO.StreamWriter file = new System.IO.StreamWriter(FilePath,false);//保存数据到⽂件file.Write(data);//关闭⽂件file.Close();//释放对象file.Dispose();return FilePath;}结果是返回⼀个⽂件路径,根据具体场合可返回,也可不返回;我们来测试⼀下⽂件是否⽣成成功,我们在Main函数中调⽤这个⽅法,代码如下: static void Main(string[] args){string data = "我的数据要开始存⼊⽂件了,我好开⼼啊!覆盖了吗?好像覆盖了,真的覆盖了";String filePath = SavaProcess(data); Console.WriteLine(filePath);}运⾏结果如下:很显然,在相关⽬录下,⽣成了想对应的⽂件;我们在看看cmd中打印出了如下路径: D:\VSProject\SavaProcessToFile\SavaProcessToFile\bin\Debug\SaveDirMyFileSend20170628.txt⽣成的这个路径对我们接下来的⼯作很重要,读取⽂本数据的时候需要⽤到;【3】读取.txt⽂件数据我们再定义⼀个读取数据的⽅法:/// <summary>/// 获取⽂件中的数据/// </summary>/// <param name="args"></param>public static string fileToString( String filePath ){string strData = "";try{string line;// 创建⼀个 StreamReader 的实例来读取⽂件 ,using 语句也能关闭 StreamReaderusing (System.IO.StreamReader sr = new System.IO.StreamReader(filePath)){// 从⽂件读取并显⽰⾏,直到⽂件的末尾while ((line = sr.ReadLine()) != null){//Console.WriteLine(line);strData = line;}}}catch (Exception e){// 向⽤户显⽰出错消息Console.WriteLine("The file could not be read:");Console.WriteLine(e.Message);}return strData;}看见没?我们这边传⼊的参数就是⽣成⽂件的那个路径,注意,参数的类型是String表⽰⽂本的,⽽不是string表⽰字符串的,因为我再⽣成路径的时候就是⽤的String,所以这⾥对应起来;接下来,我们来测试⼀下,看我们有没有读取⽂件成功,看cmd中是否会出现我们最初写⼊的那个字符串?我们在Main函数中调⽤⽅法,代码如下: static void Main(string[] args){string data = "我的数据要开始存⼊⽂件了,我好开⼼啊!覆盖了吗?好像覆盖了,真的覆盖了";String filePath = SavaProcess(data);string strData = fileToString(filePath);Console.WriteLine(strData);}运⾏结果如下:结果出现了最开始存的那个字符串;【4】写⼊和读取过程完整代码using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace SavaProcessToFile{class Program{/// <summary>/// 保存数据data到⽂件的处理过程;/// </summary>/// <param name="data"></param>public static String SavaProcess(string data) {System.DateTime currentTime = System.DateTime.Now;//获取当前⽇期的前⼀天转换成ToFileTimestring strYMD = currentTime.AddDays(-1).ToString("yyyyMMdd");//按照⽇期建⽴⼀个⽂件名string FileName = "MyFileSend" + strYMD + ".txt";//设置⽬录string CurDir = System.AppDomain.CurrentDomain.BaseDirectory + @"SaveDir"; //判断路径是否存在if(!System.IO.Directory.Exists(CurDir)){System.IO.Directory.CreateDirectory(CurDir);}//不存在就创建String FilePath = CurDir + FileName;//⽂件覆盖⽅式添加内容System.IO.StreamWriter file = new System.IO.StreamWriter(FilePath,false);//保存数据到⽂件file.Write(data);//关闭⽂件file.Close();//释放对象file.Dispose();return FilePath;}/// <summary>/// 获取⽂件中的数据/// </summary>/// <param name="args"></param>public static string fileToString(String filePath){string strData = "";try{string line;// 创建⼀个 StreamReader 的实例来读取⽂件 ,using 语句也能关闭 StreamReader using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath)) {// 从⽂件读取并显⽰⾏,直到⽂件的末尾while ((line = sr.ReadLine()) != null){//Console.WriteLine(line);strData = line;}}}catch (Exception e){// 向⽤户显⽰出错消息Console.WriteLine("The file could not be read:");Console.WriteLine(e.Message);}return strData;}static void Main(string[] args){string data = "我的数据要开始存⼊⽂件了,我好开⼼啊!覆盖了吗?好像覆盖了,真的覆盖了"; String filePath = SavaProcess(data);string strData = fileToString(filePath);Console.WriteLine(strData);}}}本⽂源于zhuxiaoge(),如有转载请标明出处,不甚感激!!!。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
很显然,根据以上程序,利用循环,可以逐行读取整个文件内容。
三、统计文件的行数 #include <iostream> #include <fstream> using namespace std; int CountLines(char *filename) { ifstream ReadFile; int n=0; char line[512]; ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件 if(ReadFile.fail())//文件打开失败:返回 0 { return 0; } else//文件存在 { while(!ReadFile.eof()) { ReadFile.getline(line,512,'\n'); n++; } return n; } ReadFile.close(); } void main() { cout<<"comn.txt 的行数为: "<<CountLines("comn.txt")<<endl; cin.get(); } 以上程序的设计思路没有问题,但在实际操作的时候会发现统计出的行数与实际不符,原因在于 ReadFile.getline(line,512,'\n')这一句: 当一行字符超过 512 或遇到回车之后, 行数自动加 1.如果换行 符在新的一行, 返回的结果会比实际多 1; 如果不在新的一行, 返回结果与实际相符。 可以修改如下: #include <iostream> #include <fstream> #include <string> using namespace std; int CountLines(char *filename) { ifstream ReadFile;
实际文件行数両
参数 行数両
参数 行数両
return "Error 1: 行数错误,不能为 0 或负数。";
return "Error 3: 行数超出文件长度。";
file流 把一行文本 读入到 string temp
while(getline(file,temp)&&i<line-1) { i++; }
这个方法读取的文件,所有字符都一起显示,不会分行。这里字母 z 显示两次,是正常的,因为在输 出文件最后一个字母 z 之后,又输出了一次(可以仔细考虑程序代码)。 读取文件某一行内容:
#include <iostream> #include <fstream> #include <string> using namespace std; int CountLines(char *filename) { ifstream ReadFile; int n=0; string tmp; ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件 if(ReadFile.fail())//文件打开失败:返回 0 { return 0; } else//文件存在 { while(getline(ReadFile,tmp)) { n++; } return n; } ReadFile.close(); } string ReadLine(char *filename,int line) { int lines,i=0; string temp; fstream file; file.open(filename,ios::in); lines=CountLines(filename); if(line<=0) { } if(file.fail()) { return "Error 2: 文件不存在。"; } if(line>lines) { }
二进制模式
ios::nocreate
打开一个文件时,如果文件不存在,不创建文件。
ios::noreplace
打开一个文件时,如果文件不存在,创建该文件
ios::trunc
打开一个文件,然后清空内容
ios::ate
打开一个文件时,将位置移动到文件尾
文件指针位置在 c++中的用法:
ios::beg
文件头
file.seekg(-10,ios::cur);
//让文件指针从当前位置向文件开始方向移动 10 个字节
file.seekg(10,ios::beg);
//让文件指针定位到离文件开头 10 个字节的位置
常用的错误判断方法:
good()
如果文件打开成功
bad()
打开文件时发生错误
eof()
到达文件尾
来自: /ctralt/blog/item/cde79fec87f841302697911c.html
for(i=1;i<=26;i++)//将 26 个数字及英文字母写入文件 { if(i<10) { in<<"0"<<i<<"\t"<<a<<"\n"; a++; } else { in<<i<<"\t"<<a<<"\n"; a++; } } in.close();//关闭文件 } 打开 com.txt,效果如下:
二、读取文件 上面仅仅是将文本写入文件,并没有读取出来。
以下为读取文件的一种方法:将文件每行内容存储到字符串中,再输出字符串 #include <iostream> #include <fstream> using namespace std; void main() { char buffer[256]; fstream out; out.open("com.txt",ios::in); cout<<"com.txt"<<" 的内容如下:"<<endl; while(!out.eof()) { out.getline(buffer,256,'\n');//getline(char *,int,char) 表示该行字符达到 256 个或遇到换行就结束 cout<<buffer<<endl; } out.close(); cin.get();//cin.get() 是用来读取回车键的,如果没这一行,输出的结果一闪就消失了 }
i是干嘛用的丠丠 i初始化为0 是循环变量両両
file.close(); return temp; } void main() { int l; char filename[256]; cout<<"请输入文件名:"<<endl; cin>>filename; cout<<"\n 请输入要读取的行数:"<<endl; cin>>l; cout<<ReadLine(filename,l); cin.get(); cin.get(); }
int n=0; char line[512]; 用不到両両 string temp; ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件 if(ReadFile.fail())//文件打开失败:返回 0 { return 0; } else//文件存在 { while(getline(ReadFile,temp)) { n++; } return n; } ReadFile.close(); } void main() { cout<<"comn.txt 的行数为: "<<CountLines("comn.txt")<<endl; cin.get(); } 四、读取文件数据到数组 #include <iostream> #include <fstream> #include <string> using namespace std; int CountLines(char *filename)//获取文件的行数 { ifstream ReadFile; int n=0; string temp; ReadFile.open(filename,ios::in);//ios::in 表示以只读的方式读取文件 if(ReadFile.fail())//文件打开失败:返回 0 { return 0; } else//文件存在,返回文件行数 { while(getline(ReadFile,temp))
逐个字符的读取文件:
#include <iostream> #include <fstream> using namespace std; void main() { fstream in; char c; in.open("comn.txt",ios::in); while(!in.eof()) { in>>c; cout<<c; } in.close(); cin.get(); }
fstream 提供了三个类,用来实现 c++对文件的操作。(文件的创建、读、写)。 ifstream -- 从已有的文件读 ofstream -- 向文件写内容 fstream - 打开文件供读写 文件打开模式: ios::in 读
ios::out