有人可以帮我将数据插入.csv文件吗?
我编写的代码将数据写入.csv文件。
我正在尝试在其中显示客户端的IP地址。但它显示如图所示。
但我希望我的.csv文件显示为,
这是将数据写入.csv文件的代码。
//included all header files
int main()
{
int new_sockfd,new1_sockfd,x1,x2,log,n;
int server_len, client_len;
struct sockaddr_in serveraddress;
struct sockaddr_in client_address;
int buffsize=1024;
char buffer2[1024];
if((new_sockfd = socket(AF_INET,SOCK_STREAM,0))>0)
printf("\n ***************************** Interface Server *******************************\n");
printf("\n Socket was created\n");
serveraddress.sin_family = AF_INET;
serveraddress.sin_addr.s_addr = inet_addr("127.0.0.1");
serveraddress.sin_port = ntohs(9735);
server_len = sizeof(serveraddress);
bind(new_sockfd, (struct sockaddr *)&serveraddress, server_len);
listen(new_sockfd, 5);
while(1)
{
char ch;
printf("\n\n Interface Server waiting...\n");
client_len = sizeof(client_address);
new1_sockfd = accept(new_sockfd,(struct sockaddr *)&client_address, &client_len);
if (new1_sockfd==-1) { perror("Connection Not Accepted!!"); return(1);}
else
printf("\n Task agent is connected\n");
//*********************
//displays client adddress
FILE * I= fopen("final_report.csv","a+");
fprintf(I,"%s,",inet_ntoa(client_address.sin_addr));
fclose(I);
//*********************
printf("\n Final Report has been generated\n\n");
log=open("final_report.csv",O_CREAT|O_RDWR|O_APPEND,0777);
if(log==-1)
{
perror("cannot open the Final Report\n");
return(1);
}
do
{
x1=read(new1_sockfd, buffer2,1024);
x2=write(log,buffer2,x1);
}
while (x1>0);
close(log);
close(new1_sockfd);
}
}
基本上使用我的程序,客户端地址只显示在一行,但我需要在每一行。
因为我使用多台客户机来发送数据,所以我需要找出哪个客户端(IP地址)已经发送了它。
我试过了,但无法找到解决方法。有人可以指导我这样做。提前谢谢。
答案 0 :(得分:0)
从长远来看,也许是fprintf(I,“%s”,inet_ntoa(client_address.sin_addr))写的数据;语句被缓冲并被覆盖,删除地址。也许调用fflush可以解决问题。
你能分享这行中读取的原始数据(buffer2的内容) x1 = read(new1_sockfd,buffer2,1024);
答案 1 :(得分:0)
如果您逐行阅读,则可以阅读一行CSV数据, 将其解析为字段,并插入您之前喜欢的任何字段 写出结果。 - 蒂姆皮尔斯
为此,请将printf("\n Task agent is connected\n");
之后的代码更改为
//*********************
FILE *I = fopen("final_report.csv", "a+"), *stream = fdopen(new1_sockfd, "r");
if (!I)
{
perror("cannot open the Final Report");
return 1;
}
while (fgets(buffer2, sizeof buffer2, stream))
//displays client adddress
fprintf(I, "%s,%s", inet_ntoa(client_address.sin_addr), buffer2);
fclose(I);
//*********************
printf("\n Final Report has been generated\n\n");
fclose(stream);
}
}