c - 如何正确解析文本文件?

标签 c file parsing pointers printing

我有一个文本文件,其中包含我编写的程序中的一堆随机数据:

hdfs45 //the hdsf part stays the same everytime, but the number always changes

我试图将这行数据解析为两部分,hdfs 部分和 45 部分(稍后转换为 int)

我尝试过类似的方法:

Char * a, * b;
char str[100];
FILE* ptr;

ptr = fopen("test.txt","r"); // opens sucessfully

while(fgets(str,100,file))
{
    a = strtok(str," \n");
    printf("%s",a); // but this prints the whole string

}

数据是随机的,将分隔符设置为“45”是没有用的。然而,第一部分“hdfs”始终是相同的,任何帮助将不胜感激。

最佳答案

如果“hdfs”永远不会改变,那么您只需将前4个后面的字符转换为数字即可,即:

int num = atoi(str + 4);
str[4] = '\0';

在您的示例中,num 将等于 45str 将等于 hdfs

关于c - 如何正确解析文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28971474/

相关文章:

python - 使用 python 比较一个文件与另一个文件是否缺少条目

javascript - Moment JS 解析奇怪的行为

c - 在 C 中这个 int 到 float 的转换有什么问题?

c - ANSI C 中的接口(interface)/实现

C:结构声明中允许成员之间的操作吗?

Java Web 服务 : sending files using DataHandler class

c - MbedTLS 和 .NET BouncyCaSTLe 与 Curve25519 的互操作性问题

c - 从代表不同值的不同文件访问 C 中的相同宏

xml - 去解析无效的 XML

parsing - Groovy - 方法的不明确方法重载