您实际上是在编写 unix/linux 实用程序“uniq”的核心功能。
cat filename | sort | uniq > newfile
#or skip sort, since you didn't mention
cat filename | uniq > newfile
你可以只使用 popen 和 uniq (类似这样的......)
FILE *uniqfh;
uniqfh = popen("cat file1 | uniq" , "r");
if (uniqfh == NULL) { //handle error
}
while( fgets(uniqfh, buffer, buffersize) ) printf("%s\n",buffer);
但是说真的,你可以写 uniq() 的核心,
static long MAXUNIQ=79; //or whatever you want
char*
isdup(char* prev, char* next, long len)
{
//if( !prev || !next) error
long n = len<=0 ? MAXUNIQ : len;
for( ; *prev==*next && n --> 0; ) { //down-to operator (sic)
; //clearly nothing happening here!
}
return( (n<1) || !(*p+*n) );
}
/yeah, this is actually strncmp, but hey
您需要一个“字符串”数组(char* 或 char[]),让我们阅读它们,
char* ray[ARRAYMAX]; //define how many elements of your arRay
//could use, char** ray; and malloc(ARRAYMAX*sizeof(char*))
long
read_array(FILE* fh, char* ray[])
{
char buffer[MAXLINE+1];
long count=0;
while( fgets(buffer,sizeof(buffer),fh) ) {
//you could eat dups here, or in separate function below
//if( (count<1) && !isdup(ray[count-1],buffer,MAXUNIQ) )
ray[count++] = strdup(buffer);
}
//ray[0] through ray[count-1] contain char*
//count contains number of strings read
return count;
}
long
deleteIdents(long raysize, char* ray[]) //de-duplicate
{
long kept, ndx;
for( ndx=1, kept=0; ndx<raysize; ++ndx ) {
if( !isdup(ray[kept],ray[ndx]) ) {
ray[kept++] = ray[ndx];
}
else {
free(ray[ndx]);
ray[ndx] = NULL; //not entirely necessary,
}
}
return kept; //new ray size
}
你需要这个来调用它...
...
long raysize;
char* ray[ARRAYMAX] = {0}; //init to null pointers
raysize = read_array(fopen(filename,"r"),ray);
raysize = deleteIndents(raysize,ray);
...
稍后,您将需要释放 malloc 的字符串,
for( ; 0 <-- raysize; ) { free(ray[raysize]); ray[raysize] = NULL; }