在C中逐行读取文件 [英] Reading file Line By Line in C

查看:139
本文介绍了在C中逐行读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前言:

这个问题是关于逐行读取文件并将每行插入到链表中的.

This question is about reading a file, line by line, and inserting each line into a linked list.

我已经编写了链表的实现,并手动测试了 insert()函数.这行得通. 我还编写了用于从文件读取文本并将其写出的代码.同样,这也有效.

I have already written the implementation for the linked list, and tested the insert() function manually. This works. I have also written the code for reading text from a file, and writing it out. Again, this also works.

好的:这是我的问题

如何合并这些概念,并编写一个从文件中逐行读取文本的功能,并将每行插入为链表中的一个节点 ?

How can I merge these concepts, and write a function that reads text from a file, line by line, and inserts each line as a node in the linked list?

从文件中读取时,我将执行以下操作:

When reading from a file, I do the following:

//Code for reading a file
int c;
while((c = getc(f))!= EOF) {
    putchar(c);  //Prints out the character
}
fclose(f);  //Close the file

insert()函数采用两个参数,一个参数是链接列表的头节点,第二个参数是要保存在该节点中的dataEntry(字符串").

The insert() function takes two parameters, one being the linked list head node, and the second one being the dataEntry ("string") to be held in that node.

void insert(node_lin *head, char *dataEntry) { ... }

因此,由于函数getc分别获取每个字符,而putchar将每个字符写到屏幕上,因此我想代码可以按照以下方式做一些事情:

Hence, since the function getc gets each character separately, and the putchar writes out each character to the screen, I imagine the code to do something along these lines:

  • 读取每个字符,直到文件结尾(EOF)
  • 对于每个字符,直到到达新行('\ n'),请将其附加到先前读取的字符(构建字符串")
  • 如果到达该行的末尾,则将此字符串"插入到链接列表中
  • 重复直到达到EOF

  • Read each character until the end of file (EOF)
  • For each character, until reaching a new line ('\n'), append this to the previously read characters (building a "string)
  • If reaching the end of the line, insert this "string" into the linked list
  • Repeat until reaching EOF

 //Code for reading a file
 int c;
 while((c = getc(f))!= EOF) {
      //Build a string here consisting of characters from c, until reaching a new line.
      /*
      if(c == '\n') {  //Indicates a new line
          //Insert the line you have into the linked list: insert(myLinkedList, line);
      }
      */
 }
 fclose(f);  //Close the file

问题是,我已经有一个正常的read_file函数以及一个正常的insert()函数.我需要帮助的是将文件分成几行,然后将其插入.

The thing is, I already have a working read_file function, as well as a working insert() function. The thing I need help with is separating the file into lines, and inserting these.

谢谢大家!

推荐答案

将字符逐个阅读替换为更高级的内容.

Replace your character-by-character reading by something more high-level.

  • 最典型的选择是 fgets() ,但这需要您指定线长度的静态限制.
  • 如果您具有 getline() ,则可以使用它,它将处理任何行长度,但它是POSIX,而不是标准C.

此外,您应该更改您的insert()函数以接受const char *作为第二个参数(当然,请记住要在内部分配内存并复制文本).

Also, you should change your insert() function to accept const char * as the second argument (and remember to allocate memory inside and copy the text, of course).

这篇关于在C中逐行读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆