aboutsummaryrefslogtreecommitdiffstats
path: root/src/easydir.c
blob: 6de77bc83d2da279c09c40a93c56ef088b915b9f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>

#include "easydir.h"
#include "handerror.h"

int checkFileExist(char *source)
{
	FILE *file = fopen(source, "r+"); // r+ so that errno can equal EISDIR
	if(!file)
		return errno == EISDIR ? F_ISDIR : F_NOEXIST;
	fclose(file);
	return F_NOEXIST;
}

char *fileCropLineFeed(char *path, char *text, int maxlen)
{
	FILE *file = fopen(path, "r+");	
	if(file == NULL) callError(130);
	
	int symbol;
	int pos = 0;
	char *str = (char *) malloc(sizeof(char) * maxlen);
	while((symbol = fgetc(file)))
	{
		switch(symbol)
		{
			case '\n':
			case EOF: {
				str[pos] = '\0';
				pos = -1; // for break while
				break;
			}
			default: {
				str[pos] = symbol;
				pos++;
				break;
			}
		}
		if(pos == -1) break;
		if(pos > maxlen-1) { str[pos-1] = '\0'; break; }
	}
	fclose(file);

	strcpy(text, str);
	free(str);
	return text;
}