简体   繁体   English

用C进行读,逐行操作和写出的最佳方法是什么?

[英]What's the best way to read in, operate line-by-line, and write out in C?

Suppose I have two text files in.txt and out.txt . 假设我有两个文本文件in.txtout.txt

in.txt : in.txt

abc      one    2    3    4
         two    3    4    two    twenty
         three  3    20   8
adbc     two    4    28   3      thirty

How can I read line-by-line and operate when necessary? 如何逐行阅读并在必要时进行操作? So that on any line I can check if it has some text in the first column ("abc" and "adbc" in this example), what's in the second column, third column, etc. until that line ends? 这样一来,我就可以检查第一行中是否有一些文本(在此示例中为“ abc”和“ adbc”),第二列,第三列中的内容等,直到该行结束为止? Then, based on those operations write into out.txt ? 然后,根据这些操作将内容写入out.txt

For example, if any line has its 6th column (if it has a 6th column) and it says "twenty" then print to out.txt "Hello." 例如,如果任何行的第6列(如果有第6列)都显示为“二十”,则打印到out.txt “你好”。

or 要么

If the second column is "three" add the following three numbers... 如果第二列是“三”,请添加以下三个数字...

I don't know about BEST way but here's one way: 我不了解BEST方式,但这是一种方式:

Read the file in and use strtok to parse it split up by delimiters. 读入文件并使用strtok解析由定界符分割的文件。 (Then you can use strtok again to read it split up by whitespace) (然后,您可以再次使用strtok读取它,并按空格分开)

http://www.cplusplus.com/reference/cstring/strtok/ http://www.cplusplus.com/reference/cstring/strtok/

I think strtok can still get the job done. 我认为strtok仍然可以完成工作。 Just follow two different paths based on lines beginning with spaces. 只需遵循两条以空格开头的不同路径即可。

pseudo code: 伪代码:

while (line = readline()) {
    if (line[0] == ' ') { // you can check for multiple spaces if necessary.
        // If line begins with empty first column
        tokenize_handle_normal(line);
    } else {
        // If line begins with string in the first column
        tokenize_handle_special(line); // Call tokenize_handle_normal(line) after parsing the first column
    }
}

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

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