135 lines
2.3 KiB
C
135 lines
2.3 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <unistd.h>
|
|
#include <fcntl.h>
|
|
|
|
#define BUFF_SIZE 1024
|
|
#define NAME_SIZE 64
|
|
#define STDIN 0
|
|
#define STDOUT 1
|
|
|
|
typedef unsigned long long u64;
|
|
|
|
char name[NAME_SIZE];
|
|
char buffer[BUFF_SIZE];
|
|
char* buffer_tail = buffer; // points on first free symbol
|
|
|
|
char iseof = 0;
|
|
|
|
int namecmp(char* name1, char* name2)
|
|
{
|
|
for (; *name1 && *name2; name1++, name2++)
|
|
{
|
|
if (*name1 != *name2)
|
|
{
|
|
return 0;
|
|
}
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
int openfile(char* filename)
|
|
{
|
|
int file = open(filename, O_RDONLY);
|
|
if (file < 0)
|
|
{
|
|
puts("Something went wrong while opening file\n");
|
|
exit(1);
|
|
}
|
|
return file;
|
|
}
|
|
|
|
void fill_buffer(int filedesc)
|
|
{
|
|
const size_t tofill = BUFF_SIZE - (buffer_tail - buffer);
|
|
u64 bytes_read = read(filedesc, buffer, tofill);
|
|
if (bytes_read < BUFF_SIZE)
|
|
{
|
|
iseof = 1;
|
|
}
|
|
buffer_tail = buffer + bytes_read;
|
|
}
|
|
|
|
char* find_second_word(char* start)
|
|
{
|
|
for (; *start != ' '; start++);
|
|
return ++start;
|
|
}
|
|
|
|
char* find_fullname_end()
|
|
{
|
|
char* end = buffer;
|
|
for (; (*end != '\n' || *end == 0)
|
|
&& end < buffer + BUFF_SIZE; end++);
|
|
if (end == buffer + BUFF_SIZE)
|
|
{
|
|
return NULL;
|
|
}
|
|
return end;
|
|
}
|
|
|
|
void pop_fullname() // pops from buffer
|
|
{
|
|
char* end = find_fullname_end() + 1;
|
|
u64 fullname_len = end - buffer;
|
|
size_t i = 0;
|
|
for (; i < BUFF_SIZE - fullname_len; i++)
|
|
{
|
|
buffer[i] = end[i];
|
|
end[i] = 0;
|
|
}
|
|
buffer_tail -= fullname_len;
|
|
}
|
|
|
|
void print_count(u64 count)
|
|
{
|
|
write(STDOUT, "count: ", 8);
|
|
while (count)
|
|
{
|
|
char digit = (count % 10) + '0';
|
|
count /= 10;
|
|
write(STDOUT, &digit, 1);
|
|
}
|
|
write(STDOUT, "\n", 1);
|
|
}
|
|
|
|
int get_name(char* accumulator)
|
|
{
|
|
char* start = find_second_word(buffer);
|
|
char* end = start;
|
|
for (; *end != ' '; end++);
|
|
if (!end)
|
|
{
|
|
return -1;
|
|
}
|
|
for (size_t i = 0; &start[i] < end; i++)
|
|
{
|
|
accumulator[i] = start[i];
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
int main(int argc, char* argv[])
|
|
{
|
|
int filedesc = openfile(argv[1]);
|
|
read(STDIN, name, sizeof(name)/sizeof(name[0]));
|
|
// fgets(name, sizeof(name)/sizeof(name[0]), stdin);
|
|
size_t count = 0;
|
|
char namebuff[NAME_SIZE] = {0, };
|
|
do
|
|
{
|
|
if (!find_fullname_end())
|
|
{
|
|
fill_buffer(filedesc);
|
|
}
|
|
get_name(namebuff);
|
|
if (namecmp(namebuff, name))
|
|
{
|
|
count++;
|
|
}
|
|
pop_fullname();
|
|
} while (buffer_tail != buffer);
|
|
print_count(count);
|
|
return 0;
|
|
}
|