0

For instance: if the input file "input.txt" is

Joanne,F,500421
Bob,M,48392
Ashley,F,1030381

I am trying to open the file, and read the name part up to comma and store that into a char array, then skip over the comma, the M or F and the next comma, then store the number into a int. I need to do this for every line up to the 100th line. Here is what I have so far, and I know it's wrong, obviously, because it doesn't work.

void processFile(char theFile[11]) {

    FILE *inputFile = fopen(&theFile[11], "r");
    int line = 1;
    char tempName[MAXNAMELEN];
    fscanf(inputFile, "%s%[^,]\n", tempName);
    printf("%s", tempName);
    line++;

    fclose(inputFile);

}


int main(void) {
    char names[MAXNAMES][MAXNAMELEN];
    int ranks[MAXNAMES][YEARS];
    int totalNames = 0;

    //Init ranks array to all -1 values
    memset(ranks, -1, sizeof(ranks[0][0]) * MAXNAMES * YEARS);

    //Process all files
    processFile("yob1930.txt");
}


So I want the name "Joanne" to be stored in a char[] and the number 500421 into an int. Then move to next line and repeat for the first 100 lines.

Jacob
  • 113
  • 1
  • 10
  • That is known as a [*Comma-Separated Values (CSV)*](https://en.wikipedia.org/wiki/Comma-separated_values) file. If you search a little you will find many duplicates. – Some programmer dude Jul 13 '17 at 06:54
  • I have found some but I want to do it without using strtok. – Jacob Jul 13 '17 at 06:55
  • 1
    if you want to use `fscanf()`, try `" %31[^,],%*c,%d"` for the format string (assuming your MAXNAMELEN is 32). This would be straight-forward using `fgets()` and `strtok()` instead. –  Jul 13 '17 at 06:56
  • "*I have found some but I want to do it without using strtok.*" <- why? it's easier to write a somewhat fault-tolerant solution with `fgets()`, `strtok()` and `strtol()`. –  Jul 13 '17 at 06:59
  • FILE *inputFile = fopen("yob1930.txt", "r"); char tempName[MAXNAMELEN]; int tempRank; fscanf(inputFile, " %[^,],%d", tempName, tempRank); printf("%s - %d\n", tempName, tempRank); – Jacob Jul 13 '17 at 07:06
  • I got the name without commas, now how about the int? – Jacob Jul 13 '17 at 07:06
  • 1
    Use the format string from my comment above. The `%*c` will consume the single character M or F without assigning the result to a variable (that's what the `*` is for). –  Jul 13 '17 at 07:11
  • my MAXNAMELEN is 20, and each name is going to be a different length, utilizing the format string you provided produces a segmentation fault. – Jacob Jul 13 '17 at 07:18
  • I do get what's going on in your format string, and I feel like it should work perfectly, but it isn't – Jacob Jul 13 '17 at 07:19
  • 1
    well, then write `%19[^,]` instead :o –  Jul 13 '17 at 07:26
  • I just read up and learned how to use strtok, wow problem solved. Lol thanks – Jacob Jul 13 '17 at 07:30
  • 1) `fopen(&theFile[11], "r");` --> `fopen(theFile, "r");` – BLUEPIXY Jul 13 '17 at 07:55

0 Answers0