adding file.c file.h and fix ccc.c %s is null
This commit is contained in:
parent
0699fc2200
commit
dca031c1f3
4 changed files with 101 additions and 2 deletions
2
Makefile
2
Makefile
|
@ -3,7 +3,7 @@
|
|||
|
||||
TARGET = ccc
|
||||
MANPAGE = ccc.1
|
||||
SRC = ccc.c util.c
|
||||
SRC = ccc.c util.c file.c
|
||||
|
||||
# Flags
|
||||
LDFLAGS = $(shell pkg-config --libs ncurses)
|
||||
|
|
2
ccc.c
2
ccc.c
|
@ -135,7 +135,7 @@ void list_cwd_files()
|
|||
{
|
||||
// memory allocation failed
|
||||
perror("ccc");
|
||||
fprintf(stderr, "ccc: Cannot read filename %s.", filename);
|
||||
fprintf(stderr, "ccc: Cannot read filename %s.", ep->d_name);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
// can't be strncmp as that filter out dotfiles
|
||||
|
|
84
file.c
Normal file
84
file.c
Normal 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
15
file.h
Normal 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
|
Loading…
Reference in a new issue