writeBuffer.c
1.14 KB
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
#include <stdio.h> /* for ferror() */
#include <string.h> /* for memset and stuff */
int
writeBuffer(char ** buffer, unsigned int * readPos, FILE * wHandle)
{
char * nlpos = strchr(*buffer, '\n');
int written = 0;
while (NULL != nlpos) {
unsigned int moveSize, clearSize;
char * actAddr;
*nlpos = '\0';
if (0 != strlen(*buffer)) {
/* write remaining stuff to file */
fputs(*buffer, wHandle);
if (ferror(wHandle)) {
return -1;
}
fputc('\n', wHandle);
if (ferror(wHandle)) {
return -1;
}
fflush(wHandle);
if (ferror(wHandle)) {
return -1;
}
written += strlen(*buffer) + 1;
}
actAddr = *buffer + *readPos;
moveSize = actAddr - nlpos - 1;
clearSize = actAddr - *buffer - moveSize;
memmove(*buffer, nlpos+1, moveSize);
memset(*buffer + moveSize, 0, clearSize);
*readPos = moveSize;
nlpos = strchr(*buffer, '\n');
}
return written;
}