I am relatively new to C and Unix and I am trying to create a function that will print the first 10 words of a file without using the stdio.h
library and instead use system calls.
So far I am reading one character at a time and I want to add that character to a struct variable (i.e concatenate if it is not a white space character). I am running into a segmentation fault, however.
Currently strcat();
gives me Program received signal SIGSEGV, Segmentation fault.
Do I need to allocate my strings/structs in some other way?
Context:
struct word{
char *content;
int length;
};
void openRead(){
char curChar;
//open file
int infile = open("sample.txt", O_RDONLY);
// set count
int count = 10;
//create array of words
struct word words[count];
struct word firstWord;
firstWord.length = 0;
firstWord.content = "test\0";
words[0] = firstWord;
int totalLen = lseek(infile, 0, SEEK_END);
lseek(infile, 0, SEEK_SET);
int i = 0;
int curCount = 1;
//-1 due to terminating character
while (curCount < count && i < totalLen-1){
// read next character
int p= lseek(infile, i, SEEK_SET);
read(infile, &curChar, 1);
int spaceCheck = isspace(curChar);
// if regular character add to word
if(spaceCheck == 0){
struct word curWord = words[curCount];
curWord.length = curWord.length + 1;
// conver character to string for string concatenation
char cToStr[2];
cToStr[1] = '\0';
cToStr[0] = curChar;
strcat(curWord.content, cToStr); // segmentation fault
words[curCount] = curWord;
} else { // create new word
struct word newWord;
newWord.length = 1;
newWord.content = &curChar;
words[curCount] = newWord;
}
i++;
}
close(infile);
}
int main()
{
openRead();
}