如何使用与fgets()和存储使用char指针阵列的文件的每一行? [英] How to use fgets() and store every line of a file using an array of char pointers?

查看:131
本文介绍了如何使用与fgets()和存储使用char指针阵列的文件的每一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为了读取文件的每一行,然后每行存储字符指针供以后使用的阵列中(如排序仅指针不是真正的字符串)写了下面的程序。 但问题是,它一直保存在同一行。

I wrote the program below in order to read every line of the file and then store each line in a array of char pointers for later use (like sorting only the pointers not the real strings). But the problem is that it keeps storing the same line.

可以说,该文件名为 file.txt的的,有两个(2)行文本。

Lets say that the file is called file.txt and has two(2) lines with text.

  first sentence
  second sentence

在code我写如下:

The code I wrote is the following:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>

int main(){
    FILE *cf;
    cf = fopen("file.txt", "r");
    char line[101];
    char *lines[2];
    char *eof;

    int i=0;
    while((eof = fgets(line, 101, cf)) != NULL){
        lines[i] = eof;
        i++;
    }

    printf("%s\n", lines[0]);
    printf("%s\n", lines[1]);

    system("pause");
    return 0;
}

我得到的输出是:

The output I get is:

second sentence
second sentence

不过,我想获得:

But I want to get:

first sentence
second sentence

我做错了的是什么?

What I am doing wrong here?

- 谢谢您的帮助: - )

-Thanks for your help :-)

推荐答案

功能与fgets 不分配新的内存。因此,在成功 EOF ==行的情况下 - 这是正确的,它会返回你传递什么。您每次都覆盖掉。

The function fgets doesn't allocate new memory. So in case of success eof == line - that's right, it returns what you passed. You are overwriting it every time.

尝试:

while((eof = fgets(line, 101, cf)) != NULL){
    lines[i] = strdup(eof);
    i++;
}

当然,你必须记住免费(行[I])

这篇关于如何使用与fgets()和存储使用char指针阵列的文件的每一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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