C:尝试将文件中的字符作为float读取

时间:2014-12-17 09:13:18

标签: c

使用gcc

在Ubuntu 12.04上运行

我有一个文本文件,其中包含10个完全如下所示的值:

  <00> 0020.50 0020.49 0020.47 0020.46 0020.51 0020.50 0020.50 0020.49 0020.49 0020.50

我想在缓冲区中读取这些值,然后想对它进行一些计算。所有值都必须被视为Floats。

所以我做的是我首先在缓冲区buffer中读取10个字符,然后使用atof()将每个值从字符转换为float并存储在bufferFloat中。但我发现bufferFloat没有正确的值。

这是我的代码:

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

using namespace std;

int main()
{
FILE *fp;
int i,x;
int read;

char * buffer;

buffer=(char *)malloc(20);

fp=fopen("Xvalues.txt","r");

read=fread(buffer,1,10,fp);

printf("no. of bytes read %d", read);

float bufferFloat[10];
int j; 

for(j=0;j<10;j++)
{

    bufferFloat[j]=atof(&buffer[j]); //converting characters to buffers 


}

int k;

for (k=0;k<10;k++)
{

    printf("printing buffers as floats: %f \n", bufferFloat[k]);

}

fclose(fp);
return 0;
}

输出

root@ubuntu:/home/ravi/Desktop/New/build# ./new1 
file opened sccesfully
no. of bytes read 10printing buffers as floats: 20.500000 
printing buffers as floats: 20.500000 
printing buffers as floats: 20.500000 
printing buffers as floats: 0.500000 
printing buffers as floats: 0.500000 
printing buffers as floats: 50.000000 
printing buffers as floats: 0.000000 
printing buffers as floats: 0.000000 
printing buffers as floats: 0.000000 
printing buffers as floats: 0.000000 
root@ubuntu:/home/ravi/Desktop/New/build# 

这不是我们在文本文件中存储的内容。

请帮我解决这个问题。

提前致谢。

以下是我使用标记化修改后的代码

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

int main()

{

FILE * fp ;

int read;
int i;

char * buffer;
buffer = (char *)malloc(2000);

fp=fopen("Xvalues.txt", "r");
if(fp==NULL)

{

printf("error reading the file");

}



//storing one line  in  buffer using fgets
if (fgets(buffer, 80, fp)!=NULL){

//    puts(buffer) ;

    }


//Tokanizing 


const char s[2]= " ";

//get the first token  

char * token;
token = strtok(buffer, s);


while (token!=NULL)
{

//printf("%s\n", token);
token  = strtok(NULL, s);

}


//converting to float
float bufferFloat[10000]; 
float ret;
ret =strtof(buffer, bufferFloat); 

for(i=0; i< 10; i++)
{
printf("float values are%f\n", bufferFloat[i]); 
}

fclose (fp);
return 0; 


}

输出仍然不正确

root@ubuntu:/home/ravi/Desktop/New# gcc test.c 
test.c: In function ‘main’:
test.c:44:7: warning: assignment makes pointer from integer without a cast [enabled by default]
test.c:51:8: warning: assignment makes pointer from integer without a cast [enabled by default]
test.c:60:1: warning: passing argument 2 of ‘strtof’ from incompatible pointer type [enabled by default]
/usr/include/stdlib.h:173:14: note: expected ‘char ** __restrict__’ but argument is of type ‘float *’
root@ubuntu:/home/ravi/Desktop/New# ./a.out 
float values are0.000000
float values are0.000000
float values are0.000000
float values are0.000000
float values are0.000000
float values are0.000000
float values are0.000000
float values are0.000000
float values are0.000000
float values are0.000000
root@ubuntu:/home/ravi/Desktop/New# 

4 个答案:

答案 0 :(得分:2)

通过read 10 characters in a buffer之类的操作不会在float中为您提供10 buffer [或其他]。这不是您应该从文件中读取的方式。我的建议是

  1. 使用fgets()从文件中读取一行。

  2. 使用strtok()使用适当的分隔符[在您的情况下为空格]来标记化读取缓冲区。

  3. 使用strtof()(优于atof())将每个标记转换为浮动并存储到数组中。

  4. 笔记:

    1. fgets()读取并存储尾随\n。标记化时要小心。 2. fgets()中提供的缓冲区应该很长,以便从文件中保存完整的输入。 功能

    另外,值得一提的是,请在通话结束后fopen()检查NULL,检查fp来电是否成功。同样适用于fread()


    编辑:

    下面的工作代码。

    #include<stdio.h>
    #include<stdlib.h>
    #include <string.h>
    
    #define MAXVAL 1024
    
    int main()
    
    {
            FILE * fp  = NULL;
            int read = 0;
            int i = 0;
            char * token = NULL;
    
            char buffer[MAXVAL] = {0};
            float bufferFloat[10] = {0}; //better way, use dynamic allocation
    
            fp=fopen("Xvalues.txt", "r");
            if(fp==NULL)
            {
                    printf("error opening the file");
                    return -1;      //don't continue
            }
    
            //storing one line  in  buffer using fgets
            if ( ! fgets(buffer, MAXVAL, fp) ){
                printf("error reading the file");
                return -2;      //don't continue
            }
            //Tokanizing 
            const char *s = " \n";      //because of fgets() stroing \n
            //get the first token  
    
            token = strtok(buffer, s);
            i = 0;
            while (token!=NULL)
            {
                    bufferFloat[i++] = strtof(token, NULL);     //I used NULL used for simplicity, you follow the proper way.
                    token  = strtok(NULL, s);
            }
    
            for(i=0; i< 10; i++)
            {
                    printf("float values are%f\n", bufferFloat[i]);
            }
    
            fclose (fp);
            return 0;
    }
    

    使用

    进行编译
    gcc test.c --std=c99
    

    运行

    ./a.out
    

    输出:

    [sourav@broadsword temp]$ ./a.out 
    float values are20.500000
    float values are20.490000
    float values are20.469999
    float values are20.459999
    float values are20.510000
    float values are20.500000
    float values are20.500000
    float values are20.490000
    float values are20.490000
    float values are20.500000
    [sourav@broadsword temp]$ 
    

答案 1 :(得分:1)

如果您提到固定号码,可以使用fscanf()

指南 - http://www.tutorialspoint.com/c_standard_library/c_function_fscanf.htm

假设 - 每行10个数字且不会改变

解决方案

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


int main(){

FILE *fp;
char read;

fp=fopen("Xvalues.txt","r");


float array[10];

int i;

 do{
    read=fscanf(fp,"%f %f %f %f %f %f %f %f %f %f",&array[0],&array[1],&array[2],&array[3],&array[4],&array[5],&array[6],&array[7],&array[8],&array[9]);
    fclose(fp);

    for(i=0 ; i< 10 ;i++){
        printf("%f ",array[i]);
    }
    printf("\n");

 }while(read != EOF);

 return 0;
}

输出

  

20.500000   20.490000   20.469999   20.459999   20.510000   20.500000   20.500000   20.490000   20.490000   20.500000

答案 2 :(得分:0)

如果数据已写入float文件,那么最好使用fscanf()以适当的格式获取数据。

答案 3 :(得分:0)

阅读使用fgets()使用strod()的行来解析它。

任何时候输入数据都在中,请考虑fgets()

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

#define MAX_EXPECTED_FLOAT_WIDTH (7)
#define MAX_EXPECTED_LINE_WIDTH(n)  (n * (MAX_EXPECTED_FLOAT_WIDTH + 1) + 2)

int ReadNfloat(FILE *stream, float *dest, int n) {
  char buffer[MAX_EXPECTED_LINE_WIDTH(n) * 2];  // I like 2x buffers
  if (fgets(buffer, sizeof buffer, stream) == NULL) {
    return -1;
  }
  char *p = buffer;

  for (int i=0; i<n; i++) {
    char *endptr;
    double number = strtod(p, &endptr);
    if (p == endptr) {  // no conversion
      return i;
    }

    // Code could do various tests. like to see if in expected range.
    if (number < 0 || number > 9999.99) {
      return i;
    }

    dest[i] = (float) number;
    p = endptr;
  }

  // Detect extra garbage
  while (isspace((unsigned char) *p) p++;
  if (*p) {
    return -1; 
  }

  return n;
}