Advertisement
balrougelive

Untitled

Aug 10th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. /*
  2. Homework 13
  3.  
  4. Only submit the .c file.
  5.  
  6. Write a C program that opens the employees.txt file for reading.
  7.  
  8. This file must be added to your project.
  9.  
  10. Write a loop that reads all employees from the file and prints the data to the console.
  11.  
  12. Close the file.
  13.  
  14. HINT: If you are having issues retrieving the name after the first time in the loop,
  15. try entering a space after the format specifier in the last call to fscanf within the loop.
  16. i.e. It should be something like this fscanf(filePtr, "%f ", &someFloat); or use fgetc()
  17. */
  18.  
  19. #pragma warning(disable : 4996)
  20. #include <stdio.h>
  21. #define FIELD_SIZE 30
  22. #define NAME_SIZE 30
  23.  
  24. int main()
  25. {
  26. FILE *fp; //Declare a FILE pointer variale
  27.  
  28. fp = fopen("employees.txt", "r"); //fopen opens the txt file named in quotes, and "r" tells it to red the file as data type
  29.  
  30. char c; //declare a char var named c
  31.  
  32. while ((c = getc(fp)) != EOF) //This while loop takes the next char, and then cycles until the built in EOF end of file function. If yes, the code does not enter the loop. If no, the first line places the char onto the stream.
  33. {
  34. ungetc(c, fp);
  35. char name[NAME_SIZE];
  36. char field[FIELD_SIZE];
  37. float decimal;
  38.  
  39. fgets(name, NAME_SIZE, fp);
  40. printf("%s", name);
  41.  
  42. fgets(field, FIELD_SIZE, fp);
  43. printf("%s", field);
  44.  
  45. fscanf(fp, "%f ", &decimal);
  46. printf("%.2f\n", decimal);
  47. }
  48.  
  49. fclose(fp); //This closes the file when done
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement