Reputation: 233
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");
}
I print the matrix to check if the scanning is successful.
Upvotes: 2
Views: 440
Reputation: 40145
When row
and col
are determined
allocate by following way:
char (*jz)[col][keyLength] = malloc(row * col * keyLength);//meant char jz[row][col][keyLength]
Read from a file:
for(i = 0; i < row; ++i){
for(j = 0; j < col; ++j){
fscanf(fp, "%s", jz[i][j]);
}
}
Print the matrix:
for(i = 0; i < row; ++i){
for(j = 0; j < col; ++j){
if(j)
putchar(' ');
printf("%s", jz[i][j]);
}
putchar('\n');
}
Upvotes: 0
Reputation: 121
simple example of reading from file with fgets()
#include <stdio.h>
#include <stdlib.h>
#define LINE_LENGTH 6
int main(int argc, char** argv)
{
int i = 0;
FILE *file_ptr;
char *string=(char*)calloc(LINE_LENGTH,sizeof(char));
file_ptr = fopen("file.txt", "r");
while(1)
{
if(fgets(string, LINE_LENGTH, file_ptr) == NULL)
break;
fgetc(file_ptr);
printf("\nline[%d] = %s\n", i+1, string);
i++;
}
fclose(file_ptr);
return 0;
}
file.txt
12344 45678 99870 33389 11234
Upvotes: 1