简体   繁体   English

读取文本文件值

[英]Reading text file values

I've got the below code and am trying to read a text file which is comma delimited and need to grab the values. 我有下面的代码,并试图读取一个逗号分隔的文本文件,需要获取值。 The text file (out.txt) contains 2 numbers: 文本文件(out.txt)包含2个数字:

12.4,45.8

My code is: 我的代码是:

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

int main()
{
    system("python Grab_Values.py > out.txt");

    FILE *ptr_file;
    char buf[1000];
    int v1;
    int v2;

    ptr_file =fopen("out.txt","r");
    if (!ptr_file)
            return 1;
    while (fgets(buf,1000, ptr_file)!=NULL)
            fscanf(buf, "%d,%d\n", &v1, &v2);

    fclose(ptr_file);
    printf("%d" "\n", v1);
    return 0;
}

When compiling I get the following errors: 编译时出现以下错误:

test.c: In function âmainâ:
test.c:17:10: warning: passing argument 1 of âfscanfâ from incompatible pointer type [enabled by default]
/usr/include/stdio.h:445:12: note: expected âstruct FILE * __restrict__â but argument is of type âchar *â

I am still ac noob so its probably a simple error but I can't figure out what :( 我仍然是交流菜鸟,所以它可能是一个简单的错误,但我不知道是什么:(

You're using 'fscanf', which is used to read from a file. 您正在使用“ fscanf”,该文件用于读取文件。 I think you want to use 'sscanf' to read the input from the 'buf' char array you read the file content into. 我认为您想使用'sscanf'来读取文件内容所读入的'buf'char数组的输入。

Bonus points - you could actually just use fscanf and do away with the 'fgets'. 奖励积分-您实际上可以只使用fscanf并消除“ fgets”。

The error in the code is here, 代码中的错误在这里,

fscanf(buf, "%d,%d\n", &v1, &v2); 

fscanf() expects a FILE* , or more clearly a stream but you are giving a character pointer.. fscanf()需要一个FILE* ,或者更明确地说是一个stream但是您要提供一个字符指针。

You can use sscanf() instead, if you wanna read from character pointer 如果您想从字符指针中读取,则可以改用sscanf()

Three things are wrong with this one: 这件事有三件事是错误的:

while (fgets(buf,1000, ptr_file)!=NULL)
        fscanf(buf, "%d,%d\n", &v1, &v2);
  1. fgets already reads data, so it's not longer available for fscanf fgets已读取数据,因此fscanf不再可用
  2. you use %d as format specifier (integer), but you want to read float values (also change the type of v1 and v2 !) 您将%d用作格式说明符(整数),但您想读取浮点值(还要更改v1v2的类型!)
  3. The first argument of fscanf is the file stream, so you need to provide ptr_file there. fscanf的第一个参数是文件流,因此您需要在ptr_file提供ptr_file

So change it to: 因此将其更改为:

fscanf(ptr_file, "%f,%f", &v1, &v2);

But also note, that this text format might not work with other locales, where the comma is the decimal point! 另请注意,此文本格式可能不适用于其他语言环境,其中逗号是小数点! You should consider enclosing comma separated float values by quotation marks. 您应该考虑用引号将逗号分隔的浮点值括起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM