rickylance
rickylance

Reputation: 67

How to read in a file of mixed data types into a string in C

I am trying to read in a file that is formatted like this sample:

3 3 1.5 50
0 2 46.0 0
* 1 46.0 1
2 * 46.0 0
0 0 50.0 0 
* * 42.0 0
2 2 36.1
2 1 42 0
0 1 48.0 0
1 0 48 0

First I want to store the contents of the file in a string. Then, I want to scan through the string and see if there are any asterisks *. For some reason I can't get it to store as a string. Whenever I try to print the string, it gives me blank lines. Is there an easy way to read in data from a file and store it into a string? I will later convert the numerical data into arrays.

Code snippet:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]){ 

  FILE *id; //Input Data
  double *detect; 
  int nx, ny, i, j, k, n, count, t, frequency;
  double a;
  char val;

  n = 0;

  id = fopen(argv[1], "r");
  frequency = atoi(argv[2]);

 if(id){
   fscanf(id, "%d %d %lf %d", &nx, &ny, &a, &tn);
  }

  detect = (double *) malloc(nx*nx*4*sizeof(double)); 

  if(id){
    for(i=0; i<2; i++){
      fscanf(id,"%s", (detect+i));
    }
  }  


//~ The rest of the code is left out ~


return 0;
}

Upvotes: 2

Views: 1208

Answers (4)

Luiz Menezes
Luiz Menezes

Reputation: 819

There are several ways to do so... You can use fscanf, regular expressions, tokenizers, parse generators, finite state machines...

All have advantages and disavantages... fscanf can misbahave with invalid inputs, regular expressions might take too long to parse the whole file, a tokenizer is a complex tool and you might take a while to learn (Flex is the guy for you), and to use FSM you need to really really know what you are doing...

Upvotes: 0

RoadRunner
RoadRunner

Reputation: 26335

You can put the data into a string like this.

It uses the following:

  1. fgets to read each line from the file and store in a string buffer.
  2. malloc to allocate space for string, char *detect on the heap. Uses realloc to reallocate more space when needed.
  3. strcat to append buffer to the pointer *detect.
  4. free to deallocate memory requested by malloc().

The code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFSIZE 100
#define STARTSIZE 10

int
main(int argc, char *argv[]) {
    FILE *id;
    char *detect;
    char buffer[BUFFSIZE];
    size_t slen, currsize = STARTSIZE, len = 0;
    const char *separate = " ";

    id = fopen(argv[1], "r");
    if (!id) {
        fprintf(stderr, "%s\n", "Error reading file");
        exit(EXIT_FAILURE);
    }

    detect = malloc(currsize * sizeof(*detect));
    if (!detect) {
        printf("Error allocating memory\n");
        exit(EXIT_FAILURE);
    }


    *detect = '\0';
    while (fgets(buffer, BUFFSIZE, id) != NULL) {
        slen = strlen(buffer);
        len += slen-1;
        if (slen > 0) {
            if (buffer[slen-1] == '\n') {
                buffer[slen-1] = '\0';
            } else {
                printf("Error: Exceeded Buffer length of %d.\n", BUFFSIZE);
                exit(EXIT_FAILURE);
            }
        }

        if (currsize == len) {
            currsize *= 2;
            detect = realloc(detect, currsize * sizeof(*detect));
            if (!detect) {
                printf("Error reallocating memory\n");
                exit(EXIT_FAILURE);
            }
        }

        strcat(detect, separate);
        strcat(detect, buffer);
    }

    printf("Your string = %s\n", detect);

    free(detect);

    return 0;
}

Upvotes: 2

John Matthew
John Matthew

Reputation: 55

What I would do is create a structure of all the data type being stored in a file and create an array of that struct depending on the number of lines in the file,then using a loop I will use fread to read data into those structures and check my each data type after explicit conversion to int of all the data types with ASCII value of asterisk.

Upvotes: 1

Dinesh Suthar
Dinesh Suthar

Reputation: 148

As I Understand from the above code, You declared detect pointer as Double. In 2nd fscanf you are using "%s" to read data from files as string But detect pointer is Double type, which is causing the problem. Declare the detect pointer as char.

char *detect;

Upvotes: 1

Related Questions