//------------------------------------------------------------------- // out2file.cpp // // This program uses a high-level programming language to show // how an application can use standard UNIX library-functions, // such as open(), write(), and close(), to create a textfile. // // We ultimately want to see how to write such a program using // low-level assembly language, but often it is useful to have // a working solution first in a high-level language (so we're // sure we've identified all of the elements that are needed). // // compile using: $ g++ out2file.cpp -o out2file // execute using: $ ./out2file // confirm using: $ cat ./mycookie.dat // // programmer: ALLAN CRUSE // written on: 23 JAN 2008 //------------------------------------------------------------------- #include // for printf(), perror() #include // for open(), O_WRONLY, etc. #include // for exit() #include // for write(), close() char filename[] = "mycookie.dat"; char filedata[] = "Computer Science 210\nSpring 2008\n"; int len = sizeof( filedata ) - 1; int main( int argc, char **argv ) { // open a new file for writing int fd = open( filename, O_WRONLY | O_CREAT | O_TRUNC, 0644 ); if ( fd < 0 ) { perror( "open" ); exit(1); } // write out data to the file int nbytes = write( fd, filedata, len ); if ( nbytes < 0 ) { perror( "write" ); exit(1); } // close the file (needed to 'commit' the file's data to storage) close( fd ); }