#include #include #include #include #include typedef struct CLL { char ch; struct CLL *next; } CLL; char *readstring (int *len); int main (int argc, char **argv) { //printf is a high-level C language command to print something out //On Linux, the low-level call is called write // write (fd,buf,cnt) //fd is the file descriptor you're writing to, buf a pointer to the characters you want to write, cnt is the number of characters you want to write //In the C language, all strings are terminated with the null byte \0. But that's a C thing. The operating system prints out as many characters as you tell it to, and they're null, it prints null. char *dogname = "ROVER\nFIDO\nSPOT\n\n\n"; write (1,dogname,100); write (1,dogname,3); /* write, as a method, returns the number of bytes written. If it returns a negative number, then somethig went wrong. Usually, if a system call returns a negative number, that means an error of some sort occurred. */ /* scanf is the high-level C function for reading input, but the low-level system call is called read. read (fd,buf,cnt); fd is the file descriptor to be read from, buf is a pointer to the memory you want it to go to, and cnt is the number of bytes you want read. If you read from a keyboard, the read is automatically ended with the newline. Not so from a text file. Reading a string is not so easy from the keyboard since you don't know how many characters the user is going to type, so you don't know how big to make the buffer. End-of-file is a figure of speech, there is no such thing. Some people envision EOF as a special character or marker, but all EOF is is when you issue a read command and zero bytes were read. It is not an error. The read command just returns 0 and you conclude that EOF was reached. */ char name[5]; char *prompt = "Enter your name: "; write (1,prompt,18); /* int rl = read (0,name,5); //how many bytes were read write (1,name,5); for (int i=0; i < 5; i++) printf ("%d\n",name[i]); printf ("%d bytes were read.\n",rl); */ int fnlen; char *fullname = readstring(&fnlen); printf ("%s\n",fullname); printf ("The string is %d bytes long.\n",fnlen); return 0; } char *readstring (int *len) { CLL *L = NULL; int ct = 0; char buf; char *final; while (1) { read (0,&buf,1); if (buf=='\n') break; CLL *N = malloc (sizeof (CLL)); N->ch = buf; N->next = L; L = N; ct++; } final = malloc (ct+1); *len = ct; final[ct] = '\0'; while (ct > 0) { ct--; final[ct] = L->ch; CLL *N = L; L = L->next; free (N); } return final; }