Read text file in C

谁说我不能喝 提交于 2020-06-25 07:16:13

问题


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


来源:https://stackoverflow.com/questions/49933210/read-text-file-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!