程序代码:
/* ip数据文件可以不存在 不存在时 执行程序会按参数建立新文件 ip.exe newdata.txt */
/* 如果文件存在 要求每行一ip 行首尾不能有多余空格 不能空行 EOF之前要有换行 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void eat_word(void);
void eat_line(FILE *fp);
void read_line(FILE *fp, char *p);
int cmp(int rows, char *ip[rows], char *new);
int main(int argc, char **argv) {
char **ip, new[16] = "0.0.0.0", t[4][4];
FILE *fp;
int i, c, rows = 0;
if(argc != 2) return 1;
if(!(fp = fopen(argv[1], "r"))) {
if((fp = fopen(argv[1], "w+"))) fprintf(fp, "%s\n", new);
else return 1;
}
rewind(fp);
while(!feof(fp))
while((c = getc(fp)) != EOF) if(c == '\n') rows++;
printf("%d\n", rows);
if(!(ip = malloc(rows * sizeof(char*)))) return 1;
for(i = 0; i < rows; i++) if(!(ip[i] = malloc(12 * sizeof(char)))) return 1;
rewind(fp);
for(i = 0; i < rows; i++) {
memset(ip[i], 0, 12 * sizeof(char));
read_line(fp, ip[i]);
}
fclose(fp);
if(!(fp = fopen(argv[1], "a"))) return 1;
do {
puts("input ip:");
memset(t, 0, 16 * sizeof(char));
memset(new, 0, 16 * sizeof(char));
for(i = 0; i < 4; i++) {
scanf("%[0-9]", t[i]);
eat_word();
}
for(i = 0; i < 2; i++) strcat(t[i], ".");
for(i = 0; i < 3; i++) strcat(new, t[i]);
if(cmp(rows, ip, new)) {
rows++;
if(!(ip = (realloc(ip, rows * sizeof(char*))))) return 1;
if(!(ip[rows - 1] = malloc(12 * sizeof(char)))) return 1;
strcpy(ip[rows - 1], new);
strcat(new, ".");
strcat(new, t[3]);
fprintf(fp, "%s\n", new);
} else puts("already in data");
puts("continue? (Y / N)");
c = getchar();
eat_word();
} while(c == 'Y' || c == 'y');
for(i = 0; i < rows; i++) free(ip[i]);
free(ip);
fclose(fp);
return 0;
}
void eat_word(void) {
int c;
while((c = getchar()) != '.' && c != '\n') continue;
}
void eat_line(FILE *fp) {
int c;
while((c = getc(fp)) != '\n' && c != EOF) continue;
}
void read_line(FILE *fp, char *p) {
int i;
char t[3][4];
for(i = 0; i < 3; i++) {
fscanf(fp, "%[0-9]", t[i]);
getc(fp);
}
for(i = 0; i < 2; i++) strcat(t[i], ".");
for(i = 0; i < 3; i++) strcat(p, t[i]);
eat_line(fp);
}
int cmp(int rows, char *ip[rows], char *new) {
int flag = 1;
while(--rows >= 0) {
if(strcmp(ip[rows], new) == 0) {
flag = 0;
break;
}
}
return flag;
}