This section:
for(i=0; i<sizeof(wp); i++) {
if(wp != NULL)
fscanf(wp, "%s", &tab[i]);
else
break;
}
Is problematic.
First, there are a couple of issues with the line: fscanf(wp, "%s", &tab[i]);
It should be written as:
fscanf(wp, "%s", tab); //removed & and array notation.
Unlike int
or float
variable types, the name of your char
array (i.e. tab
) is already a pointer pointing to the address of the variable, making it unnecessary (and incorrect) to use the address of operator (&
).
Related to above... (and likely cause of segmentation fault.)
Because the definition of tab
is for a simple array of char
( char tab[BUFFER];
), the notation tab[i]
refers only to the ith byte
(or char
) of the array, not the entire array. Because of the "%s"
format specifier used, the function fscanf() expects a char *
not a char
, making tab
the correct argument to use.
If you want to use an array of lines the variable must be created as a 2D array of char:
#define NUM_LINES 100
#define LINE_LEN 80
int main() {
char tab[NUM_LINES][LINE_LEN] = {{0}}; // zero initialized array of
// NUM_LINE strings
// each of LINE_LEN-1 capacity
In the statement for(i=0; i<sizeof(wp); i++) {
sizeof(wp)
will be equal to the number of bytes of the pointer wp
, either 32 or 64 depending on the target addressing of your application. This is probably not what you intended. (or want.)
Consider a different approach:
Given you are working with text files, try using a combination of while()
and fgets() to read lines from the file. Then you can process each line based on its known syntax.
(Following example uses a single dimension char
array for simplified illustration.)
char line[some_len];
wp = fopen(some_file_name, "r");
if(wp)
{
while(fgets(line, some_len, wp))
{
// use line. In this case, just print to stdout
printf("%s\n", line);
}
fclose(wp);
}