103_pdfsam_cs2022

103_pdfsam_cs2022 - Opening a file When you open a file you...

Info iconThis preview shows pages 1–4. 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
Background image of page 1

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

View Full DocumentRight Arrow Icon
File I/O example #include <stdio.h> int main(int argc, char *argv[]) { FILE *file1, *file2; char buf[1024]; file1 = fopen(argv[1], “r”); file2 = fopen(“out.txt”, “w”); while(!feof(file1)) { fgets(buf, 1024, file1); fprintf(file2, buf); } fclose(file1); fclose(file2); return 0; }
Background image of page 2
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
Background image of page 3

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

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 01/10/2010 for the course CS 2022 at Cornell.

Page1 / 6

103_pdfsam_cs2022 - Opening a file When you open a file you...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online