Domanda

I'm trying to read tokens from a file and place them in an array. I'm doing this in multiple steps, starting with figuring out how many tokens are in the file so i can estimate how large I need to the array to be. I was able to accomplish this using the getline() function.

FILE *crack, *dic;
crack = fopen(crack_file, "r");
dic = fopen(dic_file, "r");

char *lineptr;
size_t n;

int dic_word_count, crack_word_count, crack_line_count;
dic_word_count = crack_word_count = crack_line_count = 1;

while(getline(&lineptr, &n, dic) != EOF)
{
    dic_word_count++;
}

char **dictionary = malloc(8*dic_word_count);

but when I try to do the same thing with a different file

while(getline(&lineptr,&n, crack) != EOF)
{
    crack_line_count++;
}
printf("%d",crack_line_count);

the print statement is never reached. I'm really not sure what is going on and I'm just wondering if anybody has any ideas of what's happening and a possible fix. Let me know if you'd like to see more of my code, I'm trying to keep this concise but thorough. thanks in advance.

È stato utile?

Soluzione

line needs to be initialized before the call to getline() and ...

getline() returns -1 on failure to read a line (including end-of-file condition). In the event of an error, errno is set to indicate the cause.".

Use -1 as EOF is not necessarily -1.

Ref

char *lineptr = NULL;
size_t n = 0;
...
while(getline(&lineptr, &n, dic) != -1)

Note: robust code would use

size_t dic_word_count, crack_word_count, crack_line_count;
... 
printf("%zu", crack_line_count);

Altri suggerimenti

Problems that I see:

  1. getline is not a standard C library function. I don't know which platform you are using and what the expectations are as far as memory allocation and deallocation. I would strongly suggest use of the standard C library function fgets.

  2. If getline expects a pointer to pre-allocated memory, then there is a problem since you are not allocating any memory. If getline allocates memory, you need have code to deallocate that memory. I see a problem either way.

  3. You are incrementing dic_word_count for each line you are reading and then using 8*dic_word_count in the call to malloc. Are you assuming something that translates to 8?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top