我創建了這個程序,通過計算機的目錄(給出一個地址,即C:\ Windows)進行搜索。它將文件名存儲在以26個長陣列組織的鏈接列表中(每個字母表中的一個字母)。哪裏設置我的免費();在我的C程序中?
當我運行程序時,它會根據我輸入的字母打印出文件夾的文件名。但是,當我再次打印時,它會再次打印出最後一次打印輸出以及新打印件。
例如:
進入目錄地址: C:\ WINDOWS
C:\ WINDOWS
輸入字母的搜索: SY
SY
符號
系統
System.ini
System32
輸入字母的搜索: 一個
一個
加載項
程序兼容性
AppPatch文件
AppReadiness
AsCDProc.log
符號
系統
的System.ini
System32下
輸入字母通過搜索:
我相信我的免費();是在錯誤的地方。我對C新手很邪惡,所以我仍然在學習如何正確分配內存。有人會有任何建議來幫助我解決這個問題嗎?
這裏是我的代碼:
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <stdlib.h>
//Prototyping
int fileNameBegin(const char *a, const char *b);
void returner(char directory[256], char string[32]);
void print();
//Array of Node Pointer
struct node* arrayOfLinkedLists[26];
//Main
int main() {
printf("Enter Directory Address:\n");
char str[256];
gets(str);
char letter[32];
do {
printf("Enter letters to search by:\n");
letter[0] = '\0';
gets(letter);
returner(str, letter);
print();
} while (letter[0] != '\0');
return 0;
}
//Constructing the Node Struct
struct node{
char fileName[50];
struct node *next;
};
//Narrowing Down Search
int fileNameBegin(const char *a, const char *b)
{
if(strncasecmp(a, b, strlen(b)) == 0) return 1; //not case sensitive, string comparing var a and b with String length
return 0;
}
#define DATA_MAX_LEN 50
//Adding the node (Files) to the LinkedList in Array
void addFileName(struct node **pNode, const char *c)
{
while (*pNode)
pNode = &(*pNode)->next; //It equals the address of the pointer
*pNode = malloc(sizeof **pNode);
strncpy((*pNode)->fileName,c,DATA_MAX_LEN-1); //Copying characters from String
(*pNode)->fileName[ DATA_MAX_LEN-1] = 0;
(*pNode)->next = NULL;
}
//Opening the Directory. Reading from Directory. Comparing File Name to String and Adding if there's a match
void returner(char directory[256], char string[32])
{
DIR *pDir = opendir (directory);
if (pDir)
{
struct dirent *pent;
while ((pent = readdir(pDir)))
{
if (pent->d_name[0] == '.' && (pent->d_name[1] == 0 || (pent->d_name[1] == '.' && pent->d_name[2] == 0)))
continue;
if(fileNameBegin(pent->d_name, string))
addFileName(arrayOfLinkedLists + ((int) strlwr(string)[0] - 97), pent->d_name);
}
closedir (pDir);
}
}
//I have no idea what this does.... oh, it displays it, duh.
void print(){
int i;
struct node *temp;
for(i=0 ; i < 26; i++){
temp = arrayOfLinkedLists[i];
while(temp != NULL){
printf("%s\n",temp->fileName);
temp = temp->next;
}
}
free(temp);
}
發佈文字爲圖片鏈接就是壞的。 –
題外話。您可能需要學習*很多*。但是用所有警告和調試信息編譯:'gcc -Wall -g'。使用'gdb'調試器&'valgrind' –
我剛剛下載了C-Lion,所以我會嘗試一下。我試圖將文本發佈爲文本,但正在使用的格式使其看起來非常奇怪。 –