adding file.c file.h and fix ccc.c %s is null

This commit is contained in:
Night Kaly 2024-03-09 19:18:19 +00:00
parent 0699fc2200
commit dca031c1f3
No known key found for this signature in database
GPG key ID: 8E829D3381CFEBBE
4 changed files with 101 additions and 2 deletions

View file

@ -3,7 +3,7 @@
TARGET = ccc TARGET = ccc
MANPAGE = ccc.1 MANPAGE = ccc.1
SRC = ccc.c util.c SRC = ccc.c util.c file.c
# Flags # Flags
LDFLAGS = $(shell pkg-config --libs ncurses) LDFLAGS = $(shell pkg-config --libs ncurses)

2
ccc.c
View file

@ -135,7 +135,7 @@ void list_cwd_files()
{ {
// memory allocation failed // memory allocation failed
perror("ccc"); perror("ccc");
fprintf(stderr, "ccc: Cannot read filename %s.", filename); fprintf(stderr, "ccc: Cannot read filename %s.", ep->d_name);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// can't be strncmp as that filter out dotfiles // can't be strncmp as that filter out dotfiles

84
file.c Normal file
View file

@ -0,0 +1,84 @@
#include <string.h>
#include "util.h"
// files in a link list data structure
typedef struct file {
char *filename;
// put some more useful stat here
struct file *next;
} file;
file *files = NULL;
/*
* get length of files linked list
*/
long files_len()
{
file *current = files;
int count = 0;
while (current != NULL)
{
count++;
current = current->next;
}
return count;
}
long add_file(char *filename)
{
file *current = files;
file *new_file = memalloc(sizeof(file));
char *buf = strdup(filename);
if (!buf)
{
perror("ccc");
}
new_file->filename = buf;
new_file->next = NULL;
if (current == NULL)
{
files = new_file;
return 0;
}
long index = 1;
while (current->next != NULL)
{
current = current->next;
index++;
}
current->next = new_file;
return index;
}
file *get_file(long index)
{
file *current = files;
if (index == 0)
{
return current;
}
if (index > files_len())
{
return NULL;
}
for (long i = 0; i < index; i++)
{
current = current->next;
}
return current;
}
char *get_filename(long index)
{
file *file = get_file(index);
if (!file)
{
return file->filename;
}
else
{
return NULL;
}
}

15
file.h Normal file
View file

@ -0,0 +1,15 @@
#ifndef FILE_H_
#define FILE_H_
typedef struct file {
char *filename;
// put some more useful stat here
struct file *next;
} file;
long files_len();
long add_file(char *filename);
file *get_file(long index);
char *get_filename(long index);
#endif