一个C语言读取csv的问题
问一个C语言读取csv的问题。
我用C语言来读取csv文件中的多行多列数据,用的是fgets和sscanf函数,想一次读取一行数据(包含多列),但是怎么也读不
出来。希望能给出解决方法。谢谢了。
下面是源程序。这是一个仿真软件的一个c语言程序,里面有一些是软件本身自定义的函数,可以不用管,关键是怎样一次读取csv文件中一行数据,并且把一行中的六列数据分别放到一个数组里。
#include <device/robot.h>
#include <device/servo.h>
#include <math.h>
static DeviceTag left_heel_1,left_knee_1,left_hip_2,right_hip_2, right_knee_1,right_heel_1;
static float motor_position[]={
0.0f, 0.0f, 0.0f, /* lleg */
0.0f, 0.0f, 0.0f /* rleg */
};
static float next_position[]={
0.0f, 0.0f, 0.0f, /* lleg */
0.0f, 0.0f, 0.0f /* rleg */
};
static void reset(void) {
left_heel_1=robot_get_device("left_heel_1");
left_knee_1=robot_get_device("left_knee_1");
left_hip_2=robot_get_device("left_hip_2");
right_hip_2=robot_get_device("right_hip_2");
right_knee_1=robot_get_device("right_knee_1");
right_heel_1=robot_get_device("right_heel_1");
}
int main() {
int i;
int ni;
char l[500];
FILE* file;
const char *filename;
const char *name;
int file_ended = 0;
robot_live(reset);
name=robot_get_name();
filename="tong.csv"; /* name should be "Hoap-2 walk" */
file=fopen(filename,"r"); /* 打开文件*/
if (file==NULL)
robot_console_printf("%s: unable to locate the %s file\n",name,filename);
fgets(l,500,file); /* 读取文件 */
for(;;) { /* The robot never dies! */
if (file_ended==0) { /* read the data from the current line... */
ni = sscanf(l,"%f, %f, %f, %f, %f, %f\n", &motor_position[0],&motor_position[1], &motor_position[2],&motor_position[3],&motor_position[4],&motor_position[5]); /* 将数据读入数组中*/
for(i=0;i <6;i++) /* convert to radian */
next_position[i] = motor_position[i];
servo_set_position(left_heel_1,next_position[0]);
servo_set_position(left_knee_1,next_position[1]);
servo_set_position(left_hip_2,next_position[2]);
servo_set_position(right_hip_2,next_position[3]);
servo_set_position(right_knee_1,next_position[4]);
servo_set_position(right_heel_1,next_position[5]);
}
robot_step(5000); /* run one step */
}
return 0;
}