I would like to read some fixed length string in a text file and store them in an array. The way I read the strings is by fscanf(fp,"%c",&char[]);
However, as the data are seperated by white space, I would like the array index to indicate each string instead of each character.
How would I do that? Should I use fgets() with certain length instead of fgetc()?
Thanks
#include <stdlib.h>
#include <stdio.h>
#define MAX 1000000 //one row of double = sizeof(Double) *4400
#define keyLength 15
void readKey(char* fileName)
{
FILE *fp;
int i, j;
char ch;
if ((fp = fopen(fileName, "r")) == NULL) {
printf("can not open this file!\n");
exit(1);
}
int row = 0;
while ((ch = fgetc(fp)) != EOF)
{
if (ch == '\n')
row++;
} //Count the line
rewind(fp); //Going back to the head of the matrix
int col = 0;
while ((ch = fgetc(fp)) != '\n') //(ch=fgetc(fp))!='\n'&&(ch=fgetc(fp))!='\r'
{
if (ch == ' ')
col++;
}
col++; //Count the col
char** jz = malloc(row * sizeof(char*)); //Allocate spaces
for (i = 0; i < row; i++)
jz[i] = malloc(col * keyLength*sizeof(char));
rewind(fp);
for (i = 0; i < row; i++) //Read in the data
for (j = 0; j < col * keyLength; j++) {
if (!fscanf(fp, "%c", &jz[i][j])) {
break;
}
}
//Print the matrix
for (i = 0; i < row; i++)
for (j = 0; j < col * keyLength; j++) {
printf("%c", jz[i][j]);
if (j + 1 == col) printf("\n");
}
fclose(fp);
printf("%d row, %d col ",row,col);
}
int main(void) {
readKey("keys.txt");
}


if (j + 1 == col) printf("\n");is wong.jisn't number of column.sizeof(char)is defined in the C standard as 1. Multiplying by 1 has no effect. Suggest removing that expression from this line:jz[i] = malloc(col * keyLength*sizeof(char));and any other line where this expression is being used.