forked from CoolerVoid/0d1n
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_ops.c
145 lines (110 loc) · 2.1 KB
/
file_ops.c
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#include "file_ops.h"
#include "mem_ops.h"
#include "string_ops.h"
#include "strsec.h"
//read lines of file
char *readLine(char * NameFile)
{
FILE * arq;
arq = fopen(NameFile, "r");
// todo think implement fcntl() ,toctou mitigation...
if( arq == NULL )
{
// fclose(arq);
DEBUG("error in to open() file");
exit(1);
}
char *lineBuffer=xcalloc(1,1), line[4096];
size_t len_line=0,len=0;
while( fgets(line,sizeof line,arq) )
{
len=strnlen(line,4095);
len_line+=len;
lineBuffer=xreallocarray(lineBuffer,len_line,sizeof(char));
strlcat(lineBuffer,line,len_line);
}
if( fclose(arq) == EOF )
{
DEBUG("Error in close() file %s",NameFile);
exit(1);
}
arq=NULL;
return lineBuffer;
}
// write line in file
int
WriteFile(char *file,char *str)
{
FILE *arq;
arq=fopen(file,"a");
if ( arq == NULL )
{
// fclose(arq);
DEBUG("error in WriteFile() %s",file);
exit(1);
}
fprintf(arq,"%s\n",str);
if( fclose(arq) == EOF )
{
DEBUG("error in Write() file %s",file);
exit(1);
}
arq=NULL;
return 1;
}
// return size of bytes on file , same to unix cmd "du -b file"
long FileSize(const char *file)
{
long ret;
FILE *arq;
arq = fopen(file, "r");
if ( arq == NULL )
{
// fclose(arq);
DEBUG("error in file");
return 0;
}
fseek(arq, 0, SEEK_END);
ret = ftell(arq);
if( fclose(arq) == EOF )
{
DEBUG("error in close() file %s",file);
exit(1);
}
arq=NULL;
return ret;
}
// returns random line from file
char *Random_linefile(char * namefile)
{
FILE *f;
int nLines = 0;
static char line[1024]; // think recv space to nullbyte 1023
int randLine=0,i=0;
entropy_clock(); // i set entropy seed here
memset(line,0x0,1023);
f = fopen(namefile, "r");
if ( f == NULL )
{
// fclose(f);
DEBUG("error in file");
exit(1);
}
while ( !feof(f) )
{
if(fgets(line, 1023, f)!=NULL)
nLines++;
}
randLine = rand() % nLines;
fseek(f, 0, SEEK_SET);
while (!feof(f) && i <= randLine)
if(fgets(line, 1023, f)!=NULL)
i++;
if( fclose(f) == EOF )
{
DEBUG("error in close() file %s",namefile);
exit(1);
}
f=NULL;
return line;
}