Zach M.
Zach M.

Reputation: 1194

reading first line of a file in c

I am very new to C and I am having trouble with the most fundamental ideas in C. We are starting structures and basically the assignment we are working on is to read a delimited file and save the contents into a structure. The first line of the file has the number of entries and alls that I am trying to do at the moment is get the program to read and save that number and print it out. Please do not assume I know anything about C I really am very new to this.

This code is giving me a segmentation fault

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


struct info{
  char name[100];
  char number[12];
  char address[100];
  char city[20];
  char state[2];
  int zip;
};

int strucCount;
char fileText[1];

int main(char *file)
{
  FILE *fileStream = fopen(file, "r");
  fgets(fileText, 1, fileStream);

  printf("\n%s\n",fileText);

  fclose(fileStream);

}

Here is the sample file

4
mike|203-376-5555|7 Melba Ave|Milford|CT|06461
jake|203-555-5555|8 Melba Ave|Hartford|CT|65484
snake|203-555-5555|9 Melba Ave|Stamford|CT|06465
liquid|203-777-5555|2 Melba Ave|Barftown|CT|32154

Thanks for everyones comments, they helped a lot, sorry to Jim. I am working on very little sleep and didn't mean to offend anyone, I am sure we have all been there haha.

Upvotes: 4

Views: 34333

Answers (1)

paulsm4
paulsm4

Reputation: 121849

SUGGESTION:

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

    #define MAXLINE 80
    #define MAXRECORDS 10

    struct info{
      char name[100];
      char number[12];
      char address[100];
      char city[20];
      char state[2];
      int zip;
    };

    int 
    main(int argc, char *argv[])
    {
      FILE *fp = NULL;
      int nrecs = 0;
      char line[MAXLINE];
      struct info input_records[MAXRECORDS];

      /* Check for cmd arguments */
      if (argc != 2) {
        printf ("ERROR: you must specify file name!\n");
        return 1;

      /* Open file */
      fp = fopen(argv[1], "r");
      if (!fp) {
        perror ("File open error!\n");
        return 1;
      }

      /* Read file and parse text into your data records */
      while (!feof (fp)) {
        if (fgets(line, sizeof (line), fp) {
          printf("next line= %s\n", line);
          parse(line, input_records[nrecs]);
          nrecs++;
        }
      }

      /* Done */
      fclose (fp);
      return 0;
    }    
  fclose(fileStream);

}

Key points:

  • Note use of "argc/argv[]" to read input filename from command line

  • line, nrecs, etc are all local variables (not globals)

  • Check for error conditions like "filename not given" or "unable to open file"

  • Read your data in a loop, until end of input file

  • Parse the data you've read from the text file into an array of binary records (TBD)

Upvotes: 3

Related Questions