2

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. enter image description here enter image description here

5
  • you can try fread. size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) Commented Sep 28, 2016 at 4:57
  • if (j + 1 == col) printf("\n"); is wong. j isn't number of column. Commented Sep 28, 2016 at 6:16
  • from the man page for fscanf(): On success, these functions return the number of input items success‐ fully matched and assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure. The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set to indicate the error. Commented Sep 30, 2016 at 0:28
  • in general the posted code logic is quite 'iffy' as it assumes that each line of the input contains the same number of columns. the posted code assumes that each column is the same width. The posted code assumes that each line has the same number of columns. None of these assumptions are backed by the question text. Commented Sep 30, 2016 at 0:36
  • the expression: 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. Commented Sep 30, 2016 at 0:37

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.