C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- 格式:pdf
- 大小:447.06 KB
- 文档页数:11
用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语言中文件读写的基本操作,包括文件的打开、关闭、读取、写入和定位等。
文件的打开和关闭是文件读写的首要步骤。
可以使用标准库中的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语言统计文件中的字符数、单词数以及总行数统计文件的字符数、单词数以及总行数,包括:每行的字符数和单词数文件的总字符数、总单词数以及总行数注意:空白字符(空格和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,然后遍历缓冲区,统计当前行的字符和单词数。
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语言是一种强大而广泛使用的编程语言,它提供了丰富的功能和灵活性。
在许多应用程序中,我们需要从外部文件中读取数据并将其存储在数组中以便进行进一步处理。
本文将介绍如何使用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#实现读写⽂本⽂件中的数据【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(),如有转载请标明出处,不甚感激!!!。
C语⾔实现⽂本⽂件的检索及计数⽂本⽂件检索及计数2题⽬要求:要求编程建⽴⼀个⽂本⽂件,每个单词不包括空格及跨⾏,单词由字符序列构成且区分⼤⼩写,完成以下功能:统计给定单词在⽂本⽂件中出现的总次数、检索输出某单词在⽂本⽂件中⾸次出现的⾏号及位置。
#include<stdio.h>#include<stdlib.h>#include<string.h>void creat(FILE* fp){char ch[1000];//输⼊⽂本内容printf("Enter the contents of this file, end with # in the start of a line.\n");fgets(ch,1000,stdin);//从标准输⼊流中读取⼀⾏//⾏⾸不为#时,将本⾏内容写⼊⽂件while(ch[0]!='#'){fputs(ch, fp);fgets(ch,1000,stdin);}}void find(FILE* fp,char word[]){int first_row, first_col;//单词第⼀次出现的位置int index =0, row =0, col =0,count =0;//依次为当前单词下标变量,⾏号,列号,指定单词出现次数char ch[1000], this_word[50];//当前⾏内容,当前单词char this_char;//当前字符//按⾏读取while(fgets(ch,1000, fp)!=NULL){row ++;col =0;//依次将本⾏字符赋给this_charfor(int i =0; i<strlen(ch); i ++){this_char=ch[i];//当前字符为字母时,将其存⼊当前单词数组if(isalpha(this_char)){this_word[index]=this_char;index++;}else{if(index !=0)//单词结束{col++;}this_word[index]='\0';//表⽰字符串的结束,这样就只显⽰index前⾯我们想要的字符,否则将显⽰全部的this_word[50],但后⾯的不是我们想要的 index =0;//以备下⼀个单词的开始//当前单词为要查找单词if(strcmp(this_word , word)==0){count++;//次数为1时,记录第⼀次出现的⾏号和列号if(count ==1){first_col = col;first_row = row;}}}}}printf("\n\nThe word you enter appears %d time(s) in total.\n",count);if(count >=1){printf("\nThis word first appears in line %d, column %d",first_row,first_col);}}int main(){FILE* fp;char word[50];fp=fopen("file_plus.txt","w+");if(fp ==NULL){printf("Unable to open this file.");exit(0);//正常运⾏程序并退出程序}creat(fp);//输⼊要查找的单词printf("\nEnter the word you want to find:\n");scanf("%s", word);//将⽂件指针重新指向开头rewind(fp);//查找单词find(fp, word);fclose(fp);return0;}关于程序中使⽤到的⼏个函数:1.fgets()函数:从指定⽂件中读取字符串,每次读取⼀⾏。
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,然后遍历缓冲区,统计当前行的字符和单词数。