简体   繁体   English

逐行读取文本文件并将每行保存在缓冲区中,而不管每行的数据类型和长度

[英]Read a text file line by line and save each line in the buffer irrespective of data type and length of each line

I want to read one line of the text file, save it to a buffer, send the buffer over a udp socket and then go and read the second line and so on.. 我想读取文本文件的一行,将其保存到缓冲区,通过udp套接字发送缓冲区,然后继续阅读第二行,依此类推。

So far, since I knew the data type of the text to be read from the text file, I had been using 到目前为止,因为我知道要从文本文件中读取的文本的数据类型,所以我一直在使用

fscanf() fscanf()函数

to read each line from the text file. 从文本文件中读取每一行。 But now I don't know the data types so it is not possible for me to use this function anymore. 但现在我不知道数据类型,因此我不再使用此功能。 Is there any other way to read text file line by line. 还有其他方法可以逐行读取文本文件。

Note: The length of each line may vary. 注意: 每行的长度可能会有所不同。

Without knowing the data type you can never know what you're going to read into your variables... Let's see, you mention that the length of each line may vary, right?. 在不知道数据类型的情况下,你永远无法知道你将要读入变量的内容......让我们看一下,你提到每行的长度可能会有所不同,对吗? So we can assume that your text file contains... text. 所以我们可以假设你的文本文件包含...文本。 That is, the the number 128 would not be represented by a single integer, but by three chars that you would read and then parse into an integer. 也就是说,数字128不会由单个整数表示,而是由您将读取的三个字符表示,然后解析为整数。

That said, there's not a lot of options there but to build a parser (you read each line and try to guess what it is based on the chars you've read, say, are there only numbers?, are there only numbers but there's a dot? are there only az characters?, are they both?) that would't be 100% reliable or just try to always know the data type beforehand (say, save the first char that you read from each line for the data type when writing the file). 也就是说,除了构建一个解析器之外没有很多选择(你读取每一行并尝试根据你读过的字符来猜测它是什么,比方说,只有数字吗?是否只有数字但是有一个点?是否只有az字符?,它们都是?)不是100%可靠或只是尝试事先总是知道数据类型(比如,保存从数据类型的每一行读取的第一个字符)在写文件时)。

A very different story goes on if your text file is not really in text, but in binary mode. 如果您的文本文件不是真正的文本文件,而是二进制模式,则会发生一个非常不同的故事。 If that's the case... well, there's nothing to do but knowing the data types beforehand. 如果是这样的话......好吧,除了事先知道数据类型之外没什么可做的。

Here is a handy code I found to read data as binary 这是一个方便的代码,我发现将数据读取为二进制

FILE *fp;
fp=fopen("c:\\test.bin", "r");
char *x = new char[10]; 
//size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE      *a_file);
fread(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM