从文件中读取文本,在数组中存储行

时间:2014-03-17 15:36:06

标签: c file text

这是我的代码。它目前从文本文件中读取,一次一行。我已经使用strcpy将每一行存储到数组“行”中。我的问题是,如何打印出这个元素?目前这段代码编译并运行,但没有输出。

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

int main()
{
    FILE *ptr_file;
    char buf[1000];
    char lines[10][500];

    //num of strings, length of strings
    char *pointertoarray = lines[0];

    ptr_file =fopen("d1.txt","r");

    fgets(buf,1000, ptr_file)!=NULL;
    strcpy(buf, lines[0]);

    fgets(buf,1000, ptr_file)!=NULL;
    strcpy(buf, lines[1]);

    fclose(ptr_file);

    printf("%s", pointertoarray);

    return 0;
}   

3 个答案:

答案 0 :(得分:2)

此:

strcpy(buf, lines[0]);

应该是:

strcpy(lines[0], buf);

要打印它,你可以这样做:

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

此外,您正在读取一个1000字符串并将其复制到500字符缓冲区......这可能不太好。调整缓冲区以使大小匹配或使用strncpy来限制你复制的字符数量,这样你就不会溢出。

在任何情况下,您可能希望使用循环来读取行而不是硬编码。您可以使用fgets读取行并使用malloc为每个新行动态分配内存。它的工作要多一些,但最后要好得多,因为它可以让你读取行数不明的文件,而不必在读取多少行之前做出决定。

答案 1 :(得分:1)

strcpy的第一个参数是目的地。想想&#34;任务&#34;

答案 2 :(得分:1)

您可能希望使用循环将其打印出来。以下将打印出阵列的所有内容。在C中,您可以使用 for while 循环。

您可能希望在main之外定义数组的大小:

#DEFINE SIZE1 1000;
#DEFINE SIZE2 10;

你可以说:

int count = 0;
int count2 = 0;
for(count1 = 0; count1 < SIZE1; count1++)
{
     for(count2 = 0; count2 < SIZE2; count2++)
    {
          printf("%c", lines[count2][count1]);
    }
       printf("\n");
}
相关问题