在 C 中读取文本文件 [英] Read text file in C

查看:55
本文介绍了在 C 中读取文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文本文件包含包含键值对的数据

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)

我尝试使用

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

但不是用逗号分隔每个值

but not it separated each value with comma

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

我该怎么做

推荐答案

正如我在评论中提到的,scanf 函数系列 具有简单的模式匹配,可用于读取您的输入:

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

使用的scanf格式说明:

  • <代码>"" 匹配任何前导空格
  • "(" 匹配左括号
  • "%32[^,]" 匹配(最多 32 个)字符除了逗号
  • "," 匹配逗号
  • %d" 匹配整数值
  • ")" 匹配右括号
  • " " 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

这篇关于在 C 中读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆