Skip to content

Instantly share code, notes, and snippets.

@ksss
Created February 19, 2012 13:46
Show Gist options
  • Save ksss/1863914 to your computer and use it in GitHub Desktop.
Save ksss/1863914 to your computer and use it in GitHub Desktop.
file
/*
file.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#define FEED "\r\n" /* windows */
/*
get file size (byte)
@name: read file name
*/
unsigned long file_size (const char *name) {
FILE *fp;
struct stat statbuf;
fp = fopen(name, "rb");
if (!fp)
return 0;
if (fstat(fileno(fp), &statbuf) == -1) {
fclose(fp);
return 0;
}
fclose(fp);
return (unsigned long) statbuf.st_size;
}
/*
count char length in file
length is not include EOF
@name: read file name
*/
unsigned long file_length (const char *name) {
FILE *fp;
unsigned long i = 0;
fp = fopen(name, "rb");
if (!fp)
return 0;
while (fgetc(fp) != EOF)
i++;
fclose(fp);
return i;
}
/*
read all string in file
result string not include EOF
@name: read file name
Note: return string need free(res)
char *p = file_read("aaa");
free(p);
*/
char *file_read (const char *name) {
FILE *fp;
char *res;
char *tmp;
/* file_size() faster than file_length() */
tmp = res = malloc((file_size(name) + 1) * sizeof(char));
if (!res)
return NULL;
fp = fopen(name, "rb");
if (!fp) {
free(res);
return NULL;
}
while ((*tmp++ = fgetc(fp)) != EOF)
/* nothig */;
*--tmp = '\0';
fclose(fp);
return res;
}
/*
count max line number in file
@name: read file name
*/
long file_lines (const char *name) {
long lines = 0;
char *read = file_read(name);
char *p = read;
if (!read)
return 0;
while (p = strstr(p, FEED)) {
p++;
lines++;
}
lines++;
free(read);
return lines;
}
/*
make new array from file
@name: read file name
example:
// fp => example.txt //
foo\r\n
bar\r\n
baz(EOF)
return: res = {
res[0] = "foo",
res[1] = "bar",
res[2] = "baz"
res[3] = NULL (end of array)
(*res = "foo\0\0bar\0\0baz")
}
Note: need free(*res) && free(res)
char **pp = file_make_array("aaa");
free(*pp);
free(pp);
*/
char **file_make_array (const char *name) {
char **res;
char *p;
size_t i = 0;
int j = 0;
const int feed_len = strlen(FEED);
/* 32bit PC: address is 4 byte, 64bit PC: address is 8 byte */
res = malloc((file_lines(name) + 1) * sizeof(res));
if (!res)
return NULL;
p = file_read(name);
if (!p) {
free(res);
return NULL;
}
while (*p) {
res[i++] = p;
res[i] = NULL;
p = strstr(p, FEED);
if (!p)
break;
for (j = 0; j < feed_len; j++)
*p++ = '\0';
}
return res;
}
/*
file.h
*/
#ifndef FILE_H
#define FILE_H 1
#if defined(__cplusplus)
extern "C" {
#endif
extern unsigned long file_size (const char *);
extern unsigned long file_length (const char *);
extern char *file_read (const char *);
extern long file_lines (const char *);
extern char **file_make_array (const char *);
#if defined(__cplusplus)
} /* extern "C" { */
#endif
#endif /* FILE_H */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment