Read text file in C

2020-08-09 06:40发布

问题:

I have text file contain data like which contain key value pairs

(Ann, 67) (Jhon, 78) (Mason, 89)
(Simon, 34) (Ruko, 23)

each item separated by space and there is a space after comma

I want to read each element and print those item one by the

(Ann, 67)
(Jhon, 78)
(Mason, 89)
(Simon, 34)
(Ruko, 23)

I tried using

while (fscanf(file, "%s", value) == 1) {
    printf(value);
}

but not it separated each value with comma

(Ann,
67)
(Jhon,
78)
(Mason,
89)

How can I do that

回答1:

As I mentioned in my comment, the scanf family of functions have simple pattern matching which could be used to read your input:

char text[32];
int value;

while (fscanf(file, " (%32[^,], %d)", text, &value) == 2)
{
    printf("Got (%s, %d)\n", text, value);
}

Explanation of the scanf format used:

  • " " matches any leading white-space
  • "(" matches the opening parenthesis
  • "%32[^,]" matches (at most 32) characters except the comma
  • "," matches the comma
  • "%d" matches the integer value
  • ")" matches the closing parenthesis


回答2:

When you make the data file you can use commas. This is an example of what that would look like:

Code

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

int main(){
    FILE *inFile;
    char name[20], str[80], *i;
    int age;

    inFile = fopen("test.txt", "r");
    if (inFile == NULL){
        printf("Error opening file");
        exit(1);
    }

    while(fgets(str, 80,inFile) != NULL){
        i = strtok(str, ", ");
        strcpy(name, i);
        puts(name);

        i = strtok(NULL, ", ");
        age = atoi(i);
        printf("%d\n", age);
    }

    return 0;
}

Text File

Ann, 67
Jhon, 78
Mason, 89
Simon, 34
Ruko, 23


回答3:

Instead of using

while(fscanf...)

You may try something like :

while ((line=getline(&line, &len, file)) != -1) {
    printf("%s", line);
}


标签: c scanf readfile