首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >遍历链表以执行某些操作

遍历链表以执行某些操作
EN

Stack Overflow用户
提问于 2021-02-27 13:07:57
回答 1查看 47关注 0票数 0

我有一个链表,其中包含一个文件的路径和它所属的groupID。我的程序在当前目录中查找常规文件,我正在尝试遍历链表,以便对链表执行某些操作。下面是我的代码:

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <string.h>

typedef struct FileGroups
{
    int groupID;
    char *path;
    struct FileGroups* next;
} FileGroups;

FileGroups *head;
int GroupID = 1;

void insert(char *path)
{
    FileGroups *temp;
    temp = (FileGroups*)malloc(sizeof(FileGroups));
    temp->groupID = GroupID++;

    temp->path = malloc(strlen(path)*sizeof(char));
    strcpy(temp->path, path);

    temp->next = head;
    head = temp;
    temp = temp->next;
}

void print()
{
    FileGroups *temp;
    temp = head;
    printf("\nLinked list: \n");
    while(temp!=NULL)
    {
        printf("%d %s\n", temp->groupID, temp->path);
        temp = temp->next;
    } 
}

void listFilesRecursively(const char *basePath)
{
    char path[1024];
    struct dirent *dp;
    DIR *dir = opendir(basePath);

    if (!dir)
    {
        return;
    }

    while ((dp = readdir(dir)) != NULL)
    {
        if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0)
        {
            struct stat sb;
            FileGroups *temp;
            temp = head;

            strcpy(path, basePath);
            strcat(path, "/");
            strcat(path, dp->d_name);

            if(stat(path, &sb) == 0 && S_ISREG(sb.st_mode))
            {
                insert(path);
                while(temp!=NULL)
                {
                    printf("Do something with %s\n", temp->path);
                    temp = temp->next;
                }
                printf("\n");
            }

            else
            {
                return;
            }
        }
    }
    closedir(dir);
}

int main()
{
    listFilesRecursively(".");

    print();

    return 0;
}

这是我运行程序时得到的输出:

我不确定我是否正确地遍历了链表,因为它看起来像是在迭代地打印出“做一些事情”,但随着每次循环,它似乎向printf("Do something\n");添加了一个额外的调用,无论以前的文件路径是什么,以及它所在的当前文件路径,我希望它只对正在添加到列表中的当前文件路径做一些事情。在它的第一次循环中,它似乎也没有做什么,因为在我们甚至在目录中的第一个文件打印出"Do printf("Do something\n");“之前就有一个换行符,最后一件事是它不会对目录中的最后一个文件做任何事情,这就是./testing.txt。提前感谢您的建议和建议!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-27 13:25:15

这是因为在构建列表时,您正在循环遍历整个列表。或者在遍历目录内容之后打印列表,或者更好的做法是在目录搜索循环中只打印一项。

代码语言:javascript
复制
while(temp!=NULL)
{
    printf("Do something with %s\n", temp->path);
    temp = temp->next;
}

应该是:

代码语言:javascript
复制
printf("Do something with %s\n", path);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66395777

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档