如何读取n个字符串并将它们存储到c中的指针数组中

时间:2014-12-27 22:14:09

标签: c arrays string pointers

char *lessons[100];
FILE *lessonsptr;

lessonsptr = fopen("lessons.txt", "r");

fscanf(lessonsptr, "%d", &N);
char str[100];
while (!feof(lessonsptr))
{
    fgets(str, 100, lessonsptr);
    lessons[i] = str;
    i++;
}

fclose(lessonsptr);

while块中,我想从文件中读取一个字符串并将其存储在lessons[i]中,但此代码会使用换行符进行扫描。我尝试了其他方法,例如使用fscanf%[^\n],但它们无效。我怎样才能让它发挥作用?

P.S。 lessons.txt中的第一行是字符串数。这就是为什么我在第6行读取整数。

3 个答案:

答案 0 :(得分:2)

您的代码在两个方面有误:

  • 您不应该阅读while(!feof(...))
  • 您需要随时制作缓冲区的副本

你可以这样做:

while (fgets(str, 100, lessonsptr)) {
    lessons[i] = malloc(strlen(str)+1); // Add 1 for '\0' terminator
    strcpy(lessons[i], str); // Copy the string into the allocated space
    i++;
}

或者,既然您知道文件中有多少行,就可以for循环到N

for (int = 0 ; i != N ; i++) {
    fgets(str, 100, lessonsptr);
    lessons[i] = malloc(strlen(str)+1);
    strcpy(lessons[i], str);
}

请注意,由于使用了动态内存分配,因此您需要在程序结束时循环调用free(lessons[i])

另一个注意事项:您也可以使用strdup,但它不是C标准库的一部分。

答案 1 :(得分:1)

there were many problems with the code.
the following compiles cleanly
However, I have not run it.

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

#define MAX_LINE_LENGTH (100)

void cleanup( char **, int );

int main()
{
    int N = 0; // count of data line in file

    FILE *lessonsptr;

    if( NULL == (lessonsptr = fopen("lesson.txt", "r") ) )
    { // then fopen failed
        perror( "fopen failed for lesson.txt" );
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful

    // get count of following lines
    if( 1 != fscanf(lessonsptr, " %d \n", &N) )
    { // then, fscanf for line count failed
        perror( "fscanf failed for line count" );
        fclose(lessonsptr);
        exit( EXIT_FAILURE );
    }

    // implied else, fscanf for line count successful

    char **lessons = NULL;
    int i = 0; // loop counter
    if( NULL == (lessons = malloc(N*sizeof(char*)) ) )
    { // then malloc failed
        perror( "malloc failed for lessons");
        fclose(lessonsptr);
        exit( EXIT_FAILURE );
    }

    // implied else, malloc successful for lessons

    // set all lessons[] to NULL
    memset( lessons, 0x00, (N*sizeof(char*) ) );

    for( i=0; i< N; i++)
    {
        if( NULL == (lessons[i] = malloc(MAX_LINE_LENGTH) ) )
        { // then, malloc failed
            perror( "malloc failed for lessons[]" );
            fclose(lessonsptr);
            cleanup( lessons, N );
            exit( EXIT_FAILURE );
        }

        // implied else, malloc successful for lessons[i]

        // clear the malloc'd memory
        memset(lessons[i], 0x00, MAX_LINE_LENGTH );
    }

    char str[MAX_LINE_LENGTH] = {'\0'};

    for( i = 0; i<N; i++)
    {
        if( NULL == fgets(str, MAX_LINE_LENGTH, lessonsptr) )
        { // then file did not contain enough lines
            perror( "fgets failed" );
            fclose(lessonsptr);
            cleanup( lessons, N );
            exit( EXIT_FAILURE );
        }

        // implied else, fgets successful

        // copy line to where lessons[i] points
        memcpy( lessons[i], str, MAX_LINE_LENGTH );

        // prep for next input line
        memset( str, 0x00, MAX_LINE_LENGTH );
    } // end for

    fclose(lessonsptr);
    cleanup( lessons, N );
    return(0);
} // end function: main

void cleanup( char **lessons, int N )
{
    int i; // loop counter
    for(i=0; i<N; i++)
    {
        free(lessons[i]);
    }
    free(lessons);
} // end function: cleanup

答案 2 :(得分:0)

这是一种方式:

    char str[100][100];
    while (!feof(lessonsptr) && i<100 )
    {
        if( !fgets(str[i], 100, lessonsptr))
            break;
        lessons[i] = str[i];
        i++;
    }

如果允许getline这可能会更好:

    while (!feof(lessonsptr) && i<100)
    {
        if(0>( lessons[i] = getline(NULL,NULL,lessonptr)))
              break;
        i++;
    }

但是因为你有变量N的课程数量 (你应该在C中使用小写的变量) 你可以像这样进行初始化。

char **lessone=NULL;  
int (*str)[100]; // if not using getline()

 /*
 ...
 */

    fscanf(lessonsptr, "%d\n", &N);  // need \n to read a whole line
    lessons=calloc(sizeof(char*),N);

    str=malloc(100*N); // if not using getline()

    while (!feof(lessonsptr) && i<N )