gpt4 book ai didi

c - 我想将字符串写入文件顶部。但它不起作用。(在c中)

转载 作者:行者123 更新时间:2023-11-30 21:12:40 26 4
gpt4 key购买 nike

我想要写入“ping”的结果。

首先,我编写命令行,然后..编写其余的 ping 结果。

像这样。

ping -c5 -W1 192.168.30.52
PING 192.168.30.52 (192.168.30.52) 56(84) 字节数据。
来自 192.168.30.52 的 64 个字节:icmp_seq=1 ttl=64 time=0.368 ms
来自 192.168.30.52 的 64 个字节:icmp_seq=2 ttl=64 time=0.408 ms
来自 192.168.30.52 的 64 个字节:icmp_seq=3 ttl=64 time=0.400 ms
来自 192.168.30.52 的 64 个字节:icmp_seq=4 ttl=64 time=0.392 ms
来自 192.168.30.52 的 64 个字节:icmp_seq=5 ttl=64 time=0.393 ms

--- 192.168.30.52 ping 统计数据 ---
发送 5 个数据包,接收 5 个数据包,0% 数据包丢失,时间 3996ms
rtt 最小值/平均值/最大值/mdev = 0.368/0.392/0.408/0.018 毫秒



但这个源结果是...命令行被写入文件末尾..

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>

#define FILE_NAME "ping.txt"
#define doSystem system

void main(void) {
FILE *fp;
char cmdBuf[256], fileBuf[256], buffer[256];
char dst_addr[124] = "192.168.30.52";
struct in_addr ipaddr;

ssize_t read;
size_t len = 0;

if( !inet_aton(dst_addr, &ipaddr) ) {
printf("invalid ip address\n");
} else {
sprintf(cmdBuf, "ping -c5 -W1 %s > %s", dst_addr, FILE_NAME );
fp = fopen(FILE_NAME, "a+");
fprintf(fp , "ping -c5 -W1 %s\n", dst_addr);
doSystem(cmdBuf);

fp = fopen(FILE_NAME, "r");
while(fgets(buffer, 255, (FILE*) fp)) {
printf("%s", buffer);
}
}
}

这个结果是

PING 192.168.30.52 (192.168.30.52) 56(84) 字节数据。
来自 192.168.30.52 的 64 个字节:icmp_seq=1 ttl=64 time=0.368 ms
来自 192.168.30.52 的 64 个字节:icmp_seq=2 ttl=64 time=0.408 ms
来自 192.168.30.52 的 64 个字节:icmp_seq=3 ttl=64 time=0.400 ms
来自 192.168.30.52 的 64 个字节:icmp_seq=4 ttl=64 time=0.392 ms
来自 192.168.30.52 的 64 个字节:icmp_seq=5 ttl=64 time=0.393 ms

--- 192.168.30.52 ping 统计数据 ---
发送 5 个数据包,接收 5 个数据包,0% 数据包丢失,时间 3996ms
rtt 最小值/平均值/最大值/mdev = 0.368/0.392/0.408/0.018 毫秒
ping -c5 -W1 192.168.30.52

我该如何解决这个问题???/?

最佳答案

sprintf(cmdBuf, "ping -c5 -W1 %s >> %s", dst_addr, FILE_NAME );
fp = fopen(FILE_NAME, "w");
fprintf(fp , "ping -c5 -W1 %s\n", dst_addr);
fclose(fp);
doSystem(cmdBuf);

我喜欢这样。

它有效!

感谢所有评论!

关于c - 我想将字符串写入文件顶部。但它不起作用。(在c中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42688719/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com