私はコンピュータのディレクトリ(アドレス、すなわちC:\ Windows)を検索するこのプログラムを作成しました。ファイル名は、26文字の長さの配列(アルファベットの文字の各スロット)で構成されたリンクリストに格納されます。私の自由()を設定する場所;私のCプログラムで?
私がプログラムを実行すると、入力した文字を参照してフォルダのファイル名を印刷します。ただし、2回目にすると、最後の印刷物が新しいものと一緒に印刷されます。例えば
:
ディレクトリアドレスを入力します。 C:\ Windowsの
C:\ Windowsの
はで検索する文字を入力します。
シンボル
システム SY
SY
System.ini
System32
はで検索する文字を入力します。 は
アドインが
がAPPCOMPAT
AppPatch
AppReadiness
AsCDProc.log
シンボル
システム
のSystem.ini
System32に
文字を入力します。で検索する:
私は私のfree()を信じています。間違った場所にいる私は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をダウンロードしたので、それを試してみます。私はテキストをテキストとして投稿しようとしましたが、使用しているフォーマットは非常に奇妙に見えていました。 –