/******* * readwrite.c * * an example of reading (and writing) lines of text. * *******/ #include #include #include #define MAX_CHARS_PER_LINE 256 char input_buffer[MAX_CHARS_PER_LINE + 1]; // extra char for null terminator char* readline(FILE* fileptr){ // return string from reading next line of file or NULL if no more lines. char* result = NULL; int n_bytes; if (fgets(input_buffer, MAX_CHARS_PER_LINE, fileptr) != NULL){ // copy string from input_buffer to new block of memory n_bytes = (1 + strlen(input_buffer)) * sizeof(char); result = malloc(n_bytes); // allocate memory for new string strcpy(result, input_buffer); // ... and copy it from input_buffer } return result; } FILE* openfile(char* filename){ // return open file pointer FILE* fileptr = fopen(filename, "r"); // open for reading if (fileptr == NULL){ // ... or exit with an error. printf("OOPS - error opening file '%s' \n", filename); exit(-1); // signal that an error happened. } return fileptr; } int main(){ int n = 0; char* text = NULL; char filename[] = "hound.txt"; FILE* fileptr = openfile(filename); printf("Reading '%s' ... \n", filename); while (1){ text = readline(fileptr); if (!text){ printf("... done. Read %d lines of text.\n", n); return 0; } n += 1; if (n < 10){ // print the first few lines. printf(" line %3d : %s", n, text); } } }