C-Programm – neueste Datei eines Verzeichnisses (Linux)

closeThis post was published more than three months ago. Please note that the information offered here may no longer be current and valid. Therefore, please inform yourself about this topic elsewhere. If there is any new information, you can also send me a comment. Thank you so much!

Unter Linux kann man mit dem folgendem Befehl anzeigen lassen, welche die neuste Datei ist…

ls -1tr --group-directories-first /path/to/dir/ | tail -n 1

… habe gerade versucht dies mit C zu Programmieren, ggf. findest man noch Fehler im Skript!!! :-)

PS: weitere Infos zum arbeiten mit Dateien und Verzeichnissen findest du hier -> openbook.galileocomputing.de/c_von_a_bis_z/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>

time_t st_mTime(char *dir_name) {
    struct stat attribut;

    // printf("%s\n", dir_name); /* Test Ausgabe */
    if (stat(dir_name, &attribut) == -1) {
        fprintf(stderr, "... stat-Fehler\n");
        exit(1);
    }
    if (attribut.st_mode & S_IFREG) {
        return attribut.st_mtime;
    } else {
        return 0;
    }
}

int main(int argc, char *argv[]) {
    int length;
    char dir_name[1000];
    char dir_name_1[1000];
    char dir_name_2[1000];
    DIR *dir;
    time_t t1, t2;
    struct dirent *dir_info;

    if (argc>2) {
        fprintf(stderr, "Es ist nur ein Argument (Verzeichnis) erlaubt!!!\n");
        exit(1);
    }
    if (argc==2) {
        strcpy(dir_name, argv[1]);
    } else {
        strcpy(dir_name, ".");
    }

    if ((dir = opendir(dir_name)) == NULL) {
        fprintf(stderr, "kann %s nicht öffnen", dir_name);
        exit(2);
    }

    length=strlen(dir_name);
    if ((dir_name[length]) != "/") {
        strcat(dir_name, "/");
    }

    while ((dir_info = readdir(dir)) != NULL) {
        strcpy(dir_name_1, dir_name);
        strcat(dir_name_1, (char*)dir_info->d_name );

        while ((dir_info = readdir(dir)) != NULL) {
            strcpy(dir_name_2, dir_name);
            strcat(dir_name_2, (char*)dir_info->d_name );

            t1=st_mTime(dir_name_1);
            t2=st_mTime(dir_name_2);
             if(t1!=t2) {
                if(t1>t2) {
                    strcpy(dir_name_1, dir_name_1);
                } else if (t1

Published by

voku

Lars Moelleken | Ich bin root, ich darf das!