Advertisement
Guest User

Untitled

a guest
Dec 9th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. const char *readLine(FILE *file) {
  2.  
  3. if (file == NULL) {
  4. printf("Error: file pointer is null.");
  5. exit(1);
  6. }
  7.  
  8. int maximumLineLength = 128;
  9. char *lineBuffer = (char *)malloc(sizeof(char) * maximumLineLength);
  10.  
  11. if (lineBuffer == NULL) {
  12. printf("Error allocating memory for line buffer.");
  13. exit(1);
  14. }
  15.  
  16. char ch = getc(file);
  17. int count = 0;
  18.  
  19. while ((ch != '\n') && (ch != EOF)) {
  20. if (count == maximumLineLength) {
  21. maximumLineLength += 128;
  22. lineBuffer = realloc(lineBuffer, maximumLineLength);
  23. if (lineBuffer == NULL) {
  24. printf("Error reallocating space for line buffer.");
  25. exit(1);
  26. }
  27. }
  28. lineBuffer[count] = ch;
  29. count++;
  30.  
  31. ch = getc(file);
  32. }
  33.  
  34. lineBuffer[count] = '\0';
  35. char line[count + 1];
  36. strncpy(line, lineBuffer, (count + 1));
  37. free(lineBuffer);
  38. const char *constLine = line;
  39. return constLine;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement