Your use of feof
is not necessary. You can use fgets
as the loop condition. Then it is just a matter of storing the strings in an array. You can then numerically convert your number with strtol
or atoi
(if needed). For example, you could do something like:
#define MAXL 10
#define MAXC 32
char array[MAXL][MAXC] = {{0}};
size_t index = 0;
if (!(fp = fopen (fn, "r"))) {
fprintf (stderr, "error: file open faied '%s'.\n", fn);
return 1;
}
while (fgets (data, 255,fp))
{
char *p = data;
if ((p = strtok (data, ","))) {
size_t plen = strlen (p);
if (plen + 1 < MAXC)
strncpy (array[index++], p, plen + 1);
else
fprintf (stderr, "error: string exceeded MAXC\n");
while (index < MAXL && (p = strtok (NULL, ",\n")) != NULL)
{
plen = strlen (p);
if (plen + 1 < MAXC)
strncpy (array[index++], p, plen + 1);
else
fprintf (stderr, "error: string exceeded MAXC\n");
}
}
}
Using a for Loop
You can do the same thing with a for
loop a bit more efficiently:
while (fgets (data, 255,fp)
{
char *p = data;
for (p = strtok (data, ","); index < MAXL && p; p = strtok (NULL, ",\n"))
{
size_t plen = strlen (p);
if (plen + 1 < MAXC)
strncpy (array[index++], p, plen + 1);
else
fprintf (stderr, "error: string exceeded MAXC\n");
}
}
note: by confirming the length plen
before you copy to your array, you can insure your strings are nul-terminated. Let me know if you have further questions.