Getline function
Getline function
How can i create simple getline function (like readln in Pascal) in OS written in C ? I have got keyboard driver (irq 1) and timer (irq 0). I am using DJGPP to compile and link. Can you write a simple function for me?
It's not that difficult, as long as you have a getchar like function. It would be something like this.
Note: This code isn't tested or even proven to work...
Code: Select all
char *getline() {
int i = 0;
char c;
char ret[64];
while(c != '\n') [
c = getchar();
ret[i] = c;
i++;
}
return ret;
}
C8H10N4O2 | #446691 | Trust the nodes.
I think the code might need a little optimization. Putting a terminating null at the end of the string would be good. You should put a terminating null at the end, where the '\n' character stays.
When you read with this while cycle, the '\n' character will be stored at the end. You should write the following statement after the cycle:
And then return a pointer to the array.
When you read with this while cycle, the '\n' character will be stored at the end. You should write the following statement after the cycle:
Code: Select all
ret[i-1] = '\0';
And then return a pointer to the array.
I think, I have problems with Bochs. The biggest one: Bochs hates me!
Some errors here:Alboin wrote:Note: This code isn't tested or even proven to work...Code: Select all
char *getline() { int i = 0; char c; char ret[64]; while(c != '\n') [ c = getchar(); ret[i] = c; i++; } return ret; }
* No null termination (so unless the caller is careful to only read up to \n it's going to read too much).
* Returns a local variable (the array).
* Doesn't check if the line fits into the buffer, so there's a buffer overflow if the line is longer than 64 chars (including \n).
So don't use that version.
I think the whole idea about the getchar is wrong. Or if it is not wrong, then you must find a way to use the library file (where the getchar definition stays)...However, I think also Alboin just wanted to show an example about reading lines from somewhere. And then Cmaranec - your question is answered. If somebody give you the right code, it won't work. You must adapt the algorithm to your operating system.
I think, I have problems with Bochs. The biggest one: Bochs hates me!
Very true. It was meant to be more pseudo-code than anything else.INF1n1t wrote:I think the whole idea about the getchar is wrong. Or if it is not wrong, then you must find a way to use the library file (where the getchar definition stays)...However, I think also Alboin just wanted to show an example about reading lines from somewhere. And then Cmaranec - your question is answered. If somebody give you the right code, it won't work. You must adapt the algorithm to your operating system.
C8H10N4O2 | #446691 | Trust the nodes.