简体   繁体   English

将行从文件复制到 char *array[]?

[英]Copy lines from file to char *array[]?

Hi need a little bit of help here.您好这里需要一点帮助。 I have a file with 5 lines and I want to put this lines into an array of type char *lines[5];我有一个包含 5 行的文件,我想将这些行放入一个char *lines[5]; but I can't figure it out why the following isn't working.但我无法弄清楚为什么以下内容不起作用。

#include <stdio.h>
#include <string.h>

int main(void) {
    FILE *fp = fopen("name.txt", "r");
    char *str;
    char *list[5];
    int i = 0;

    while (fgets(str, 100, fp) != NULL) // read line of text
    {
        printf("%s", str);
        strcpy(list[i], str);
        i++;
    } 
}

As the commenters stated, you need to create an array (which is nothing more than a space in the memory) of a sufficient size to store your string.正如评论者所说,您需要创建一个足够大的数组(只不过是内存中的一个空间)来存储您的字符串。 One approach to solve your problems is the following, note the comments:解决问题的一种方法如下,请注意注释:

#include <stdio.h>
#include <string.h>

    int lines(FILE *file); //try to format the code according to some standard
    int main(void) {
        FILE *fp = fopen("name.txt", "r");
        char list[5][100]; //make sure you allocate enough space for your message

// for loop is more elegant than while loop in this case, 
// as you have an index which increases anyway.
// also, you can make sure that files with more than 5 lines 
// do not break your program.
        for(int i = 0; i<5 ;++i ) 
        {
            if(fgets(list[i], 100, fp) == NULL){
               break;
            }
            //list[i] is already a string, you don't need an extra copy
            printf("%s", list[i]);
        } 
    }

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

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