Class Notes (811,485)
Canada (494,756)
CSC209H1 (41)
Karen Reid (20)


3 Pages
Unlock Document

Computer Science
Karen Reid

File interfaces in UNIX  Reading from file  UNIX has 2 main mechanisms for managing file access o If we want to read from somewhere other than stdin, we need to o file pointers: standard I/O library open a file  You deal with a pointer to a FILE structure that contains a o How should we specify the filename in a code? descriptor and a buffer  argv[0] == name of program  Use for regular files (more abstract and portable)  arvg[1] == first argument  Allows simple reading/writing/opening/closing  argvc == number of arguments given, includes argv[0] o file descriptors: low-level int main(int argc, char **argv) {  Each open file is identified by a small integer if(argc != 2) {  Use for pipes and sockets fprintf(stderr, “Usage: %s \n”, argv[0]);  stdin, stdout, stderr exit(1); o These 3 files are automatically opened for any executing program }  These are global variables in the library of type FILE * (file /* rest of code opening file */ } streams) already open and setup everytime a program is ran o stdin: Standard Input = reading from the keyboard o To open a file use:  File Descriptor = 0 FILE *fopen(const char *filename, o stdout: Standard Output = writing to screen const char *mode);  File Descriptor = 1 o stderr: Standard Rrror = write to screen for error messages  filename identifies the file to open  mode tells how to open the file:  File Descriptor = 2  "r" for reading, "w" for writing, "a" for appending  File operations o For regular files use from #include  Returns a pointer to a FILE struct which is the handle to the file  This pointer will be used in subseqeuent operations  fopen, fread, fwrite, fprintf, fgets,  FILE struct contains info of the file –ex. size, location in file fscanf, fclose  To close a file use: char *fgets(char *s, int size, FILE *stream); void fclose(File *stream); o Reads the next (whole) line from a file pointers (i.e what’s open)  It reads at most size-1 characters o ex. open a file with a list of names, call reverse_name and print the names  Reading stops after a '\n' character or EOF 1. int main(int argc, char **argv) {  Appends a '\0' character at the end of the string 2. char *sptr, name[MAX]; o fgets tries to read a string vs. fread, which tries to read bytes 3. FILE *fp;  Files and Strings 4. if(argc != 2) { o Problem: given a name in the format “Last, First”, return a string in. fprintf(stderr, "Usage: %s \n”, the format “First Last” 6. argv[0]); 1. char *reverse_name(char *src) { 7. exit(1); 8. } 2. int s_len = strlen(src) 9. if((fp = fopen(argv[1], "r")) == NULL) { 3. int dest_len = 0; 10. perror(argv[1]); 4. char *dest; 11. exit(1); 5. char *sptr = strchr(src, ','); 12. } 6. 13. while((sptr = fgets(name, MAX, fp)) != NULL) { 7. /* allocate space for return string */ 14. /* strip the newline */ 8. if ((dest = malloc(s_len+1)) == NULL) { 15. sptr = strchr(name, '\n'); 9. return NULL; 16. *sptr = '\0'; 10. } 11. 17. printf("%s\n", reverse_name(name)); 12. /* Move past the comma and the spaces 18. } 13. btwn the comma and the first name */ 19. return 0; 20. } 14. sptr++; 15. while(*sptr == ' ') {  Error Handling 16. sptr++; o Most system calls return -1 if an error occurs 17. }  A few returns NULL 18. 19. /* Copy the first name to dest */ o errno – global variable that holds the numeric code of the last 20. strncat(dest, sptr, strlen(src) + 1); system call so when a system call error occurs, errno is set 21.  Every process has errno assigned to 0 at the process creation time 22. /* Add a space to the dest string */ 23. dest_len = strlen(dest);  A successful system call never affects the current value of errno 24. dest[dest_len] = ' ';  An unsuccessful system call always overwrites the current value 25. dest[dest_len + 1] = '\0'; of errno 26. o Always check the return value of system calls 27. /* Copy the last name from src to dest */ 28. strncat(dest, src, src_len - dest_len - 1); void perror(char *str); 29. dest[src_len-1] = '\0';  perror displays str, then a colon, then an English description 30. return dest; of the last system call error in errno as defined in errno.h 31. } 32.  protocol: 33. int main() {  check system calls for a return value of -1 34. char *sptr, name[MAX];  call perror() for an error description 35. while((sptr = fgets(name, MAX, stdin)) 36. != NULL) {  Binary I/O 37. /* strip the newline */ o Recall that fgets reads characters 38. sptr = strchr(name, '\n'); o By contrast, fread and fwrite operate on bytes 39. *sptr = '\0'; 40. printf("%s\n", reverse_name(name)); size_t fread(void *ptr, size_t size, 41. } size_t nmemb, FILE *stream); 42. return 0;  Read nmeb*size bytes into memory at ptr from file pointer 43. } stream  nmeb = number of members  i.e. how many elements to read and how big each element is  Especially if it’s a text file (i.e contents = characters) b/c writing size_t fwrite(const void *ptr, size_t size, into the middle of the file = overwriting content o If we are treating a file as collection of records, it is often useful to be size_t nmemb, FILE *stream); able to move to a particular position (byte) in the file  Write nmeb*size bytes from ptr to the file pointer stream o It doesn't matter what the bytes contain  Espeically if the file contains fixed sized records, then no content is being overwritten accidently  Ex. writes  Write an integer to file int fseek(FILE *stream, long offset int num = 21; int whence); n = fwrite(&num, sizeof(num), 1, fp);  Set the file position for stream  Write a struct to the file  Add offset bytes to the position specified by whence struct rec {  whence can be char name[20]; int num;  SEEK_SET – beginning of file  S
More Less

Related notes for CSC209H1

Log In


Don't have an account?

Join OneClass

Access over 10 million pages of study
documents for 1.3 million courses.

Sign up

Join to view


By registering, I agree to the Terms and Privacy Policies
Already have an account?
Just a few more details

So we can recommend you notes for your school.

Reset Password

Please enter below the email address you registered with and we will send you a link to reset your password.

Add your courses

Get notes from the top students in your class.