简体   繁体   English

在C中逐行读取文件

[英]Reading a file line by line in C

I am trying to write some code that will open a file, read its content line by line and store each of these lines into an array. 我正在尝试编写一些代码来打开文件,一行一行地读取其内容,并将每行存储到一个数组中。

First I open the file and count the number of lines, each of the lines is of a fixed length so I simply do this : 首先,我打开文件并计算行数,每行的长度都是固定的,所以我只需要这样做:

    char buf2[LINE_LENGTH];
    int in2 = open("toSend2", O_RDONLY);
    int number_of_lines = 0;

    for (;;)
 {
  char* p2 = buf2;
  int count = read (in2, p2, LINE_LENGTH);
  if (count < 0)
  {
    printf("ERROR");
    break;
  }
  if (count == 0) break; 

  number_of_lines++;

  printf("count: %d \n",count);
  printf("File 2 line : %s", p2);
  printf("\n");

 }
 close (in2);

So far, this works well, number_of_lines is indeed the number of lines in the file "toSend2" and each of my printf are the lines contained in that file. 到目前为止,此方法运行良好,number_of_lines实际上是文件“ toSend2”中的行数,而我的每个printf都是该文件中包含的行。

Now with the number of lines, I create an array of strings and then I basically go through the whole file again but this time, I would like to store each of the lines in the array (there's probably a better way to find out the number of lines in a file, but everything that I tried has failed !) 现在有了行数,我创建了一个字符串数组,然后我基本上再次遍历了整个文件,但是这次,我想将每一行存储在数组中(可能有一种更好的方法来找出数字文件中的行数,但是我尝试的所有操作都失败了!)

    char * array[number_of_lines];
    int b=0;
    int in3=0;
    in3 = open("toSend2", O_RDONLY);
    for (;;)
 {
  char* p3 = buf3;
  int count = read (in2, p3, LINE_LENGTH);
  if (count < 0)
  {
    printf("ERRORRRRRR");
    break;
  }
  if (count == 0) break;


  array[b] = p3;
  b++;

  printf("count: %d \n",count);
  printf("FILE 2 LINEEEEEE : %s", p3);
  printf("\n");

 }  
 close(in3);

This, of course, doesn't work : each of my printf are the right line plus the last line of the file, for example, the first printf would be : 这当然是行不通的:我的每个printf都是右行加上文件的最后一行,例如,第一个printf是:

FILE 2 LINEEEEEEE : "1st line of the file" "last line of the file" FILE 2 LINEEEEEEE:“文件的第一行”“文件的最后一行”

And after this for loop, when I trace the contents of my array, every item in it is simply the last line of the file. 在此for循环之后,当我跟踪数组的内容时,其中的每个项目都只是文件的最后一行。 I think this is because I simply put the same pointer (pointing to a different line at that moment) in the array each time, but in the end it will point to the last line, therefore everything will be the last line. 我认为这是因为我每次都只是在数组中放置相同的指针(此时指向不同的行),但是最后它将指向最后一行,因此所有内容都将成为最后一行。

How would I solve my problem ? 我该如何解决我的问题?

ps: I just started C, so please do not assume I know even basic things about it :( ps:我刚开始使用C,所以请不要以为我什至不了解它:(

  • Use stdio, ie fopen() , fgets() and fclose() to do the I/O. 使用stdio,即fopen()fgets()fclose()进行I / O。 You're using much lower-level Posix-style I/O, for no good reason. 您正在使用低级Posix风格的I / O,这没有充分的理由。
  • You will need to dynamically allocate each new line in order to store it in the array. 您将需要动态分配每行,以便将其存储在数组中。 You can use strdup() to do this. 您可以使用strdup()执行此操作。
  • Remember that things can go wrong; 请记住,事情可能会出错。 files can fail to open, lines can fail to read in, and memory can fail to be allocated. 文件可能无法打开,行可能无法读入,并且内存可能无法分配。 Check for this, and act accordingly. 检查并采取相应措施。

You haven't created an array of strings, you've created a pointer to an array of strings. 您尚未创建字符串数组,而是已创建了指向字符串数组的指针。 you need to malloc your array in part2 to be count of lines * number of char's per line. 您需要在第2部分中将数组malloc分配为行数*每行的char数。 then move your read lines into each subsequent position of array. 然后将读取的行移到数组的每个后续位置。

[edit] [编辑]
one more thing..... 还有一件事.....
your strings are X length. 您的字符串是X长度。 'C' strings aren't X length, they're X+1 length :) 'C'字符串不是X长度,而是X + 1长度:)
[/edit] [/编辑]

为什么不使用fopen,然后仅使用fgets获取每一行

You can use stat to get the file size. 您可以使用stat来获取文件大小。 Then number_of_lines = stat.st_size/LINE_LENGTH 然后number_of_lines = stat.st_size/LINE_LENGTH

If you don't need your character strings nul-terminated, you can read the whole file into a single buffer. 如果您不需要以零结尾的字符串,则可以将整个文件读取到单个缓冲区中。 Set up the array of pointers if you really want them, or just use &buf[n * LINE_LENGTH] to get the start of line n . 如果确实需要它们,则设置指针数组,或者仅使用&buf[n * LINE_LENGTH]来获取第n行的开始。

To print a non-nul terminated string of known length, you can use: 要打印已知长度的非空终止字符串,可以使用:

printf("line %d = '%.*s'\n", n, LINE_LENGTH, &buf[n * LINE_LENGTH]);

Let me know in a comment if you want to see actual code. 如果您想查看实际的代码,请在评论中告诉我。

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

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