关于链表内存释放
本帖最后由 qq3397965 于 2013-03-14 01:07:18 编辑 这段代码是查询文件的.我想知道如何再查询完之后释放链表申请的内存...
对链表不是很熟悉...
谢谢各位老师...
#include "stdafx.h"
#include <STDIO.H>
#include <MALLOC.H>
#include <STRING.H>
#include <windows.h>
#include <stdlib.h>
//使用链表保存每个找到的文件夹
typedef struct DirList{
char name[256];
DirList * next;
} *LpDirList;
DirList * first, * last;
//往链表中添加节点
void add(char * name)
{
DirList *newDir = (LpDirList)malloc(sizeof(DirList));
strcpy(newDir->name, name);
newDir->next = NULL;
last->next = newDir;
last = newDir;
}
void loopFind(char * dir, char * filename)
{
char searchName[256] = {0};
char nextDir[256] = {0};
strcpy(searchName, dir);
strcat(searchName, "\\*");
//保存找到的文件或文件夹的信息的结构体
WIN32_FIND_DATA findData;
HANDLE hFindFile = FindFirstFile(searchName, &findData);
if(hFindFile != INVALID_HANDLE_VALUE)
{
do
{
if(findData.cFileName[0] == '.') continue;
if(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
strcpy(nextDir, dir);
strcat(nextDir, "\");
strcat(nextDir, findData.cFileName);
add(nextDir);
memset(nextDir, 0, sizeof(nextDir));
}
} while (FindNextFile(hFindFile, &findData));
}
//查找符合条件的文件,并输出
char nextFileName[256] = {0};
memset(searchName, 0, sizeof(searchName));
strcpy(searchName, dir);
strcat(searchName, "\");
strcat(searchName, filename);
hFindFile = FindFirstFile(searchName, &findData);
if(hFindFile != INVALID_HANDLE_VALUE)
{
do
{
strcpy(nextFileName, dir);
strcat(nextFileName, "\");
strcat(nextFileName, findData.cFileName);
printf("%s\n", nextFileName);
} while (FindNextFile(hFindFile, &findData));
}
FindClose(hFindFile);
}
//void pfree(LpDirList *head)
//{
//LpDirList *p=head;
//while(p->next!=NULL) //每次删除头节点的后继节点
//{
//q=p->next;
//p->next=q->next;
//free(q);
//}
//free (head); //最后删除头节点
// }
void search(char * dir, char * filename)
{
printf("开始搜索...\n");
first = (LpDirList)malloc(sizeof(DirList));
strcpy(first->name, dir);
first->next = NULL;
last = first;
while (first != NULL)
{
loopFind(first->name, filename);
first = first->next;
}
}
int main(int argc, char* argv[])
{
if(argv[1]==NULL || argv[2]==NULL)
{
printf("请输入目录或文件!\n");
return 0;
}
char searchName[256] = {0};
strcat(searchName, "*");
strcat(searchName, argv[2]);
strcat(searchName, "*");
search(argv[1], searchName);
system("pause");
return 0;
}
void release (LpDirList head)
{
while (head)
{
LpDirList temp = head;
head = head->next;
free(temp);
}
}