31_pdfsam_cs2022_lectures

31_pdfsam_cs2022_lectures - Opening a file When you open a...

Info icon This preview shows pages 1–6. Sign up to view the full content.

View Full Document Right Arrow Icon
Opening a file When you open a file, you specify a filename and a file mode The file mode specifies how you want to access the file Give a string indicating the mode For reading: “r” For writing: “w” For append: “a” Return value is a file handle of type FILE * FILE is a struct defined in stdio.h You pass it to subsequent file I/O routines
Image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
File I/O example #include <stdio.h> int main() { FILE *file1, *file2; char buf[1024]; file1 = fopen (“in.txt”, “r”); file2 = fopen(“out.txt”, “w”); while(!feof(file1)) { fgets (buf, 1024, file1); fprintf (file2, buf); } fclose (file1); fclose(file2); return 0; }
Image of page 2
File I/O error handling Check the return values to detect errors fopen() : returns zero on failure fclose() : returns non-zero on failure fgets() : returns zero on failure fputs() : returns non-zero on failure fprintf, fscanf() : returns negative on failure Global variable errno stores which error occurred e.g. file not found, disk full, etc. Call perror() to print a helpful error message automatically
Image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Error handling example #include <stdio.h>
Image of page 4
Image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Image of page 6
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern