简体   繁体   English

c 将文本文件逐行读入数组并打印

[英]c reading a text file into array line by line and print them

I have the following C# code snippet我有以下 C# 代码片段

string[] lines = File.ReadAllLines(@"C:\test.txt");
for(int i=0; i<lines.Length; i++)
    Console.WriteLine(lines[i]);

Can you help me to convert it to C?你能帮我把它转换成C吗?

Thanks!谢谢!

If you plan to use Ansi Standard C, you'll need fopen , fgets , and printf to do what you want.如果您打算使用 Ansi Standard C,则需要fopenfgetsprintf来执行您想要的操作。

Here's a tutorial that does almost exactly what you want .这是一个教程,几乎完全符合您的要求

Take a look at the fopen and fgets functions.查看fopenfgets函数。

fgets in particular will read until a newline character is reached, so it is perfect for reading in text files a line at a time.特别是fgets会一直读取直到遇到换行符,因此它非常适合一次读取文本文件一行。

the process should work pretty much as expected:该过程应该几乎按预期工作:

Open the file, figure out the encoding (ReadAllLines does that for you) read the input with the guessed encoding, recode it into your target format - which will probably be UTF16 - and print it to stdout...打开文件,找出编码(ReadAllLines 为您做这件事)使用猜测的编码读取输入,将其重新编码为您的目标格式(可能是 UTF16)并将其打印到标准输出...

Just for what it's worth, if you're just copying the data from one stream to another, there's no need to worry about doing it line by line -- the lines are determined by new-line characters (or carriage returns and/or carriage return/line feed combos) in the data.就其价值而言,如果您只是将数据从一个流复制到另一个流,则无需担心逐行执行 - 行由换行符(或回车和/或回车)决定返回/换行组合)在数据中。

If you simply copy the data through without changing it, the lines will be preserved.如果您只是简单地复制数据而不更改它,则将保留这些行。 To maximize speed, you probably want to open the file in binary mode, and use fread/fwrite to copy fairly large chunks (eg 4 megabytes) of data at a time.为了最大限度地提高速度,您可能希望以二进制模式打开文件,并使用 fread/fwrite 一次复制相当大的数据块(例如 4 兆字节)。

you can do it in simple way with C++.你可以用 C++ 以简单的方式做到这一点。

ifstream input("test.in");
string line;
while(getline(input, line)) {
  //Your code for the current line
}

Using fgets invites tricky edge cases:使用fgets导致棘手的边缘情况:

  • What if a line's length is greater than the size of a fixed-width buffer?如果一行的长度大于固定宽度缓冲区的大小怎么办?
  • What if the file doesn't end with a newline?如果文件不以换行符结尾怎么办?
  • What if the last line fits exactly in the buffer without causing the end-of-file status to be set?如果最后一行正好适合缓冲区而不导致设置文件结束状态怎么办?

On my blog, I posted an example of how to do it robustly with fgets .在我的博客上,我发布了一个示例,说明如何使用fgets稳健地做到这一点

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

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