我有一點問題。只有當相同的字符串/字試圖寫入時,我纔想寫入文件。在我的情況下,它的IP地址和端口用「:」隔開。如果我手動寫入文件,例如193. 。。 :80和193.。 。:22,它規定他們,但仍寫入文件。我的錯誤在哪裏:在寫入文件之前檢查文件中是否存在字符串/字
#ifdef DEBUG
#define INITIAL_ALLOC 2
#else
#define INITIAL_ALLOC 512
#endif
void BlockIP(char * s);
char *read_line(FILE *fin);
void *right_line(int p,char * s,int ssh,int http);
int main(int argc, char const *argv[])
{
//struct uci_context *uci;
//uci = uci_init();
char *ip = "193.2.2.1 193.2.6.6 193.168.1.1 193.5.5.5"
//int uci_port = atoi(ucix_get_option(uci, "pack_mon", "manual_blocking", "port"));
const char s[2] = " ";
char *token;
token = strtok(ip, s);
while(token != NULL)
{
BlockIP(token);
token = strtok(NULL, s);
}
return(0);
}
void BlockIP(char * s){
int ssh = 22;
int http = 80;
char sshbuffer[2000]= "\0";
char httpbuffer[2000]= "\0";
char cmd2[2000] = "\0";
char cmd[2000] = "\0";
snprintf(cmd, sizeof(cmd),"iptables -I INPUT 1 -p tcp -s %s --dport 80 -j REJECT",s);
snprintf(cmd2, sizeof(cmd2),"iptables -I INPUT 1 -p tcp -s %s --dport 22 -j REJECT",s);
snprintf(sshbuffer, sizeof(sshbuffer),"%s:%d", s,ssh);
snprintf(httpbuffer, sizeof(httpbuffer),"%s:%d", s,http);
FILE *fp ,*ft;
fp = popen(cmd, "r");
pclose(fp);
ft = popen(cmd2, "r");
pclose(ft);
FILE *fin;
char *line;
fin = fopen("/tmp/mymonlog", "r");
if (fin) {
while (line = read_line(fin)) {
if (strstr(line, sshbuffer)){
printf("Already exist %s\n",line);
}else{
right_line(1,s,ssh,http);
}
if(strstr(line, httpbuffer)){
printf("Already exist %s\n",line);
}else{
right_line(2,s,ssh,http);
}
free(line);
}
}
fclose(fin);
}
char *read_line(FILE *fin) {
char *buffer;
char *tmp;
int read_chars = 0;
int bufsize = INITIAL_ALLOC;
char *line = malloc(bufsize);
if (!line) {
return NULL;
}
buffer = line;
while (fgets(buffer, bufsize - read_chars, fin)) {
read_chars = strlen(line);
if (line[read_chars - 1] == '\n') {
line[read_chars - 1] = '\0';
return line;
}
else {
bufsize = 2 * bufsize;
tmp = realloc(line, bufsize);
if (tmp) {
line = tmp;
buffer = line + read_chars;
}
else {
free(line);
return NULL;
}
}
}
return NULL;
}
void *right_line(int p,char * s,int ssh,int http){
FILE *pFile,*tFile;
if(p == 1){
pFile=fopen("/tmp/mymonlog", "a");
if(pFile==NULL) {
perror("Error opening file.");
}else {
fprintf(pFile, "%s:%d\n", s,ssh);
}
fclose(pFile);
}else if(p == 2){
tFile=fopen("/tmp/mymonlog", "a");
if(tFile==NULL) {
perror("Error opening file.");
}
else {
fprintf(tFile, "%s:%d\n", s,http);
}
fclose(tFile);
}
}
主要的第一行()有沒有被定義的類型聲明:「uci_context *」。第二行有一個未定義的函數'uci_init()'。到目前爲止,這對你的問題看起來不太好:( – ThingyWotsit
uci_init()工作得很好:D。我需要它來獲取一些數據 –
你好,歡迎來到StackOverflow。請花一些時間閱讀幫助頁面,特別是名爲[「我可以在這裏問什麼問題?「](http://stackoverflow.com/help/on-topic)和[」我應該避免問什麼類型的問題?「](http://stackoverflow.com/help/dont-ask)。更重要的是,請閱讀[Stack Overflow問題清單](http://meta.stackexchange.com/q/156810/204922)。您可能還想了解[最小,完整和可驗證的示例](http:// stackoverflow .com/help/mcve) –