File and IO Extensions¶
Overview¶
The I/O extensions library provides high level file and path manipulation functions.
Features¶
Simple read, write and append text files.
File information functions.
Standard input and output redirect.
Path manipulation functions.
List files in a folder.
Reading and Writing Files¶
The library provides a simple mechanism to read and write text to files.
#include <c-craft/io.h>
MEM_SCOPE mem = sm_create(0);
char *data = "This is some data for a file";
char *extra = ", and this is appended.";
write_file("tmp.txt", data);
append_file("tmp.txt", extra);
char *buf = read_file(mem, "tmp.txt");
sm_free(mem); /* Clean up when done */
File Information¶
Check if a file exists, or find the size of an existing file.
#include <c-craft/io.h>
char *file = "myfile.txt";
if(file_exists(file))
{
long size = get_fsize(file);
printf("%s size is %ld bytes.\n", file, size);
}
else
printf("%s not found.\n", file);
Create Full Path¶
Use mkpath to create a complete folder path.
#include <c-craft/io.h>
char *path = "/tmp/this/is/a/path";
mkpath(path);
Or use mkpath_to to create a complete folder path to a file.
#include <c-craft/io.h>
char *file = "/tmp/this/is/a/path/to/myfile.txt";
mkpath_to(file);
Listing Folders¶
Folder contents may be listed like this:
#include <c-craft/io.h>
MEM_SCOPE mem = sm_create(0);
LIST_STR *files = list_dir(mem, "folder/", FALSE);
int i = 0;
char *file = list_str_first(files, NULL);
while (file)
{
printf("%s\n", file);
file = list_str_next(files, NULL);
}
sm_free(mem);
Note that ‘.’ and ‘..’ are never returned, they are implicit. Also the trailing ‘/’ for folders in this library is critical. Folder listings will show a trailing ‘/’ for sub-directory names, and failing to specify a trailing ‘/’ will result in no files found.
