Commit d9c004c6 authored by xingqiao's avatar xingqiao
Browse files

helloworld basic code files

parent 4249cde4
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char file_buffer[64*1024];
char *get(char *file_buffer, char *position, int lineCount) {
char *output = position;
int index = position - file_buffer;
while(lineCount > 0) {
if(index == 0) {
break;
}
output--;
index--;
if(file_buffer[index] == '\n') {
lineCount--;
if(lineCount == 0) {
output++;
}
}
}
return output;
}
int main(int argc, char **argv) {
if (argc != 4) {
fprintf(stderr, "usage: %s <file> <key> <lines before>\n", argv[0]);
return 1;
}
FILE *f = fopen(argv[1], "r");
if (!f) {
fprintf(stderr, "Could not open %s: ", argv[1]);
......@@ -19,12 +40,38 @@ int main(int argc, char **argv) {
fprintf(stderr, "Could not read entire file. Is it too big?\n");
return 1;
}
int lineCount = atoi(argv[3]);
char *key = argv[2];
int keylen = strlen(key);
int i = 0;
while(1) {
char *position = strstr(&file_buffer[i], key);
if (!position) {
break;
} else {
i = position - file_buffer + 1;
char *output = get(file_buffer,position,lineCount);
char temp = position[keylen];
position[keylen] = '\0';
printf("%s\n\n",output);
position[keylen] = temp;
}
}
fclose(f);
// we want this to be a null-treminated string,
// but fread just reads the file as binary, so we add it ourselves
file_buffer[bytes_read] = '\0';
// ADD YOUR CODES HERE
return 0;
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment