我想为我的序列阅读器创建一个临时配置文件 我认为我的代码不是最优的 有没有更好的方法来检测设备? 有人提示优化我的代码
此配置文件将在稍后读出 用fp = fopen(tempserv," r");
和unlink(tempserv);
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <fcntl.h>
#define MOUSEPATH "/dev/serial/by-id"
/*
example content
usb-FTDI_FT232R_USB_UART_A4011SXX-if00-port0
usb-FTDI_FT232R_USB_UART_A4022SXX-if00-port0
usb-FTDI_FT232R_USB_UART_A4033SXX-if00-port0
usb-FTDI_FT232R_USB_UART_A4044SXX-if00-port0
*/
#define EASYSTRING "usb-FTDI_FT232R_USB_UART_"
int main (void){
DIR *dir;int i = 1;
struct dirent *ent;
dir = opendir (MOUSEPATH);
char tempserv[] = "/tmp/generate.conf-XXXXXX";
int fd;fd=mkstemp(tempserv);
char tempstr[512];
char devname[62];
if (dir != NULL){
<------>while ((ent = readdir(dir)) != NULL){
<------><------>if (strstr(ent->d_name, EASYSTRING)){
<------><------><------>sprintf(devname, "%s/%s", MOUSEPATH, ent->d_name);
<------><------><------>int mtmp = open(devname, O_RDONLY);
<------><------><------>if((mtmp) > 0){
<------><------><------><------>sprintf(tempstr,"\n[reader]\nlabel = easymouse%d\nprotocol = mouse\ndevice = %s/%s\ndetect = cd\ngroup = 1\n\0", i++, MOUSEPATH, ent->d_name);
<------><------><------><------>write(fd,tempstr,strlen(tempstr));
<------><------><------><------>close(mtmp);
<------><------><------>}else{
<------><------><------><------>close(mtmp);
<------><------><------>}
<------><------>}
<------>}
} closedir (dir);
return 0;
}