我编写了这段代码,用于从传感器读取数据:
char c;
do{
while(!read(fd, &c, 1));
} while (c!='$');
do{
while(!read(fd, &c, 1));
} while (c!=',');
do{
while(!read(fd, &c, 1));
printf("%c",c);
fp = fopen("/var/www/Sensor_data.txt", "a");
fprintf(fp, "%c%", c);
fclose(fp);
} while (c!='\n');
文件看起来像这样
518.088131,0.272969,0.376242,0.522998,0.368944,0.347478,0.343025,0.252323,0.612587,0.552753,0.120302,806.230415
然后,我想要一种处理这些数据的方法,因此我将数据编号 2、3、4、5、6、7、8(粗体部分)传输到新文件中。 任何人都可以举一个执行此操作的程序的示例吗?或者更喜欢修改我的程序,以便它创建一个包含所有数据的文件,以及其他 7 个文件,每个文件包含 1 个数据。
最佳答案
像这样的事情就可以了。但可扩展性不太好:S
// This part has to go before main function starts
char int_to_char(int n){
return (char) n + (int)'0';
}
// and this replaces what you already had
int reading = 1;
do{
while(!read(fd, &c, 1)); // <- you should change this
printf("%c",c);
fp = fopen("/var/www/Sensor_data.txt", "a");
fprintf(fp, "%c", c);
fclose(fp);
if (c == ',')
reading++ ;
else{
if (reading >= 2 && reading <= 8){ // 2nd to 8th reading
char temp[] = "/var/www/Sensor_data .txt"; // <- Added a space, which I'm
// gonna substitute with a number
temp[20] = int_to_char(reading); // Substitute the space
fp = fopen(temp, "a");
fprintf(fp, "%c", c);
fclose(fp);
}
}
} while (c!='\n');
只有数字在 0 到 9 之间时,从 int 到 char 的转换才有效。
关于c - 处理数据 - C 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26674549/