Presentation is loading. Please wait.

Presentation is loading. Please wait.

Files ● System Calls and Functions – Unix: open, read,write,creat, lseek,close – Win32: CreateFile, CloseHandle, ReadFile, WriteFile, SetFilePointer ●

Similar presentations


Presentation on theme: "Files ● System Calls and Functions – Unix: open, read,write,creat, lseek,close – Win32: CreateFile, CloseHandle, ReadFile, WriteFile, SetFilePointer ●"— Presentation transcript:

1 Files ● System Calls and Functions – Unix: open, read,write,creat, lseek,close – Win32: CreateFile, CloseHandle, ReadFile, WriteFile, SetFilePointer ● Documentation:info,man, man - k,http://msdn.microsoft.com/libraryhttp://msdn.microsoft.com/library ● Unix : /var/run/utmp, /dev/tty, time, make

2 File API

3 Read/Write/Open Documentation ● who who ● read read ● write write ● open open

4 utmp ● The utmp file allows one to discover information about who is currently using the system. There may be more users currently using the system, because not all programs use utmp logging.

5 Accessing utmp utmp.h: struct utmp { short ut_type; /* type of login */ pid_t ut_pid; /* pid of login process */ char ut_line[UT_LINESIZE]; /* device name of tty - "/dev/" */ char ut_id[4]; /* init id or abbrev. ttyname */ char ut_user[UT_NAMESIZE]; /* user name */ char ut_host[UT_HOSTSIZE]; /* hostname for remote login */ struct exit_status ut_exit; /* The exit status of a process marked as DEAD_PROCESS. */ long ut_session; /* session ID, used for windowing*/ struct timeval ut_tv; /* time entry was made. */ int32_t ut_addr_v6[4]; /* IP address of remote host. */ char __unused[20]; /* Reserved for future use. */ };

6 Who int main() { struct utmp current_record; /* read info into here */ int utmpfd; /* read from this descriptor */ int reclen = sizeof(current_record); if ( (utmpfd = open(UTMP_FILE, O_RDONLY)) == -1 ){ perror( UTMP_FILE ); /* UTMP_FILE is in utmp.h */ exit(1); } while ( read(utmpfd, &current_record, reclen) == reclen ) show_info(&current_record); close(utmpfd); return 0; /* went ok */ }

7 Who /* show info() * displays contents of the utmp struct in human readable form * *note* these sizes should not be hardwired */ show_info( struct utmp *utbufp ) { printf("%-8.8s", utbufp->ut_name); /* the logname */ printf(" "); /* a space */ printf("%-8.8s", utbufp->ut_line); /* the tty */ printf(" "); /* a space */ printf("%10ld", utbufp->ut_time); /* login time */ printf(" "); /* a space */ #ifdef SHOWHOST printf("(%s)", utbufp->ut_host); /* the host */ #endif printf("\n"); /* newline */ }

8 Wh02 void show_info( struct utmp *utbufp ) { if ( utbufp->ut_type != USER_PROCESS ) return; printf("%-8.8s", utbufp->ut_name); /* the logname */ printf(" "); /* a space */ printf("%-8.8s", utbufp->ut_line); /* the tty */ printf(" "); /* a space */ showtime( utbufp->ut_time ); /* display time */ #ifdef SHOWHOST if ( utbufp->ut_host[0] != '\0' ) printf(" (%s)", utbufp->ut_host);/* the host */ #endif printf("\n"); /* newline */ }

9 time ● There are various functions for reading the system clock. See man ctime. struct tm { int tm_sec; /* seconds */ int tm_min; /* minutes */ int tm_hour; /* hours */ int tm_mday; /* day of the month */ int tm_mon; /* month */ int tm_year; /* year */ int tm_wday; /* day of the week */ int tm_yday; /* day in the year */ int tm_isdst; /* daylight saving time */ };

10 ctime void showtime( time_t timeval ) /* * displays time in a format fit for human consumption * uses ctime to build a string then picks parts out of it * Note: %12.12s prints a string 12 chars wide and LIMITS * it to 12chars. */ { char *ctime(); /* convert long to ascii */ char *cp; /* to hold address of time */ cp = ctime( &timeval ); /* convert time to string */ /* string looks like */ /* Mon Feb 4 00:46:40 EST 1991 */ /* 0123456789012345. */ printf("%12.12s", cp+4 ); /* pick 12 chars from pos 4 */ }

11 Aside:C pointer arithmetic ● float *a, b[20]; ● char *c, d[20]; ● a=b; c=d; ● *(a+1)=3.4; ● *(c+2)='a'; ● What is b[1],d[2]?

12 cp1.c: open, creat, read, write */ #include #define BUFFERSIZE 4096 #define COPYMODE 0644 void oops(char *, char *); main(int ac, char *av[]) { int in_fd, out_fd, n_chars; char buf[BUFFERSIZE]; /* check args */ if ( ac != 3 ){ fprintf( stderr, "usage: %s source destination\n", *av); exit(1); } /* open files */ if ( (in_fd=open(av[1], O_RDONLY)) == -1 ) oops("Cannot open ", av[1]); if ( (out_fd=creat( av[2], COPYMODE)) == -1 ) oops( "Cannot creat", av[2]); /* copy files */

13 open, creat, read, write while ( (n_chars = read(in_fd, buf, BUFFERSIZE)) > 0 ) if ( write( out_fd, buf, n_chars ) != n_chars ) oops("Write error to ", av[2]); if ( n_chars == -1 ) oops("Read error from ", av[1]); /* close files */ if ( close(in_fd) == -1 || close(out_fd) == -1 ) oops("Error closing files",""); } void oops(char *s1, char *s2) { fprintf(stderr,"Error: %s ", s1); perror(s2); exit(1); }

14 who3:Buffering i nt main() { struct utmp *utbufp, /* holds pointer to next rec */ *utmp_next(); /* returns pointer to next */ if ( utmp_open( UTMP_FILE ) == -1 ){ perror(UTMP_FILE); exit(1); } while ( ( utbufp = utmp_next() ) != ((struct utmp *) NULL) ) show_info( utbufp ); utmp_close( ); return 0; }

15 utmp_lib #include #define NRECS 16 #define NULLUT ((struct utmp *)NULL) #define UTSIZE (sizeof(struct utmp)) static char utmpbuf[NRECS * UTSIZE]; /* storage */ static int num_recs; /* num stored */ static int cur_rec; /* next to go */ static int fd_utmp = -1; /* read from */

16 utmp_lib utmp_open( char *filename ) { fd_utmp = open( filename, O_RDONLY ); /* open it */ cur_rec = num_recs = 0; /* no recs yet */ return fd_utmp; /* report */ } struct utmp *utmp_next() { struct utmp *recp; if ( fd_utmp == -1 ) /* error ? */ return NULLUT; if ( cur_rec==num_recs && utmp_reload()==0 ) /* any more ? */ return NULLUT; /* get address of next record */ recp = ( struct utmp *) &utmpbuf[cur_rec * UTSIZE]; cur_rec++; return recp; }

17 utmp_lib int utmp_reload() /* * read next bunch of records into buffer */ { int amt_read; /* read them in */ amt_read = read( fd_utmp, utmpbuf, NRECS * UTSIZE ); /* how many did we get? */ num_recs = amt_read/UTSIZE; /* reset pointer */ cur_rec = 0; return num_recs; } utmp_close() { if ( fd_utmp != -1 ) /* don't close if not */ close( fd_utmp ); /* open */ }

18 writing file records: lseek NAME lseek - reposition read/write file offset SYNOPSIS #include off_t lseek(int fildes, off_t offset, int whence); DESCRIPTION The lseek function repositions the offset of the file descriptor fildes to the argument offset according to the directive whence as follows: SEEK_SET The offset is set to offset bytes. SEEK_CUR The offset is set to its current location plus offset bytes. SEEK_END The offset is set to the size of the file plus offset bytes. The lseek function allows the file offse to be set beyond the end of he existing end-of-file of the file (but this does not change the size of the file). If data is later written at this point, subsequent reads of the data in the gap return bytes of zeros (until data is actually written into the gap).

19 Exercise ● Write a version of the shell command tail – see man page – implement the -n flag

20 Compiling ● gcc -o who3 who3.c utmplib.c ● gcc -g -o who3 who3.c utmplib.c ● gdb who3 ● http://msdn07.e-academy.com/ksu_cs/http://msdn07.e-academy.com/ksu_cs/

21 Win32 Open File ● http://msdn.microsoft.com/library/ http://msdn.microsoft.com/library/ ● Returned Type File Creation API API Set HANDLE CreateFile() Win32 HFILE OpenFile()/_lcreat() Win32 int _creat()/_open() C Run-time FILE * fopen() C Run-time

22 Example File Copy int main (int argc, LPTSTR argv []) { HANDLE hIn, hOut; DWORD nIn, nOut; CHAR Buffer [BUF_SIZE]; if (argc != 3) { printf ("Usage: cp file1 file2\n"); return 1; } hIn = CreateFile (argv [1], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hIn == INVALID_HANDLE_VALUE) { printf ("Cannot open input file. Error: %x\n", GetLastError ()); return 2; }

23 Win32 copy hOut = CreateFile (argv [2], GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hOut == INVALID_HANDLE_VALUE) { printf ("Cannot open output file. Error: %x\n", GetLastError ()); return 3; } while (ReadFile (hIn, Buffer, BUF_SIZE, &nIn, NULL) && nIn > 0) { WriteFile (hOut, Buffer, nIn, &nOut, NULL); if (nIn != nOut) { printf ("Fatal write error: %x\n", GetLastError ()); return 4; } CloseHandle (hIn); CloseHandle (hOut); return 0; }

24 CREATING AND OPENING FILE HANDLE CreateFile (LPCTSTR lpName, DWORD dwAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpsa, DWORD dwCreate, DWORD dwAttrsAndFlags, HANDLE hTemplateFile) Return: A HANDLE to an open file object – INVALID_HANDLE_VALUE in case of failure LPCTSTR will be described later

25 CREATING AND OPENING FILES Parameters lpName – Pointer to the string naming the file – Length normally limited to 260 – \\server\ is an escape prefix allowing long NT path names dwAccess – Access using GENERIC_READ or GENERIC_WRITE – Note: Flags can be combined with |

26 CREATING AND OPENING FILES dwCreate — Create a file, overwrite one, etc. – CREATE_NEW — Fails if the file exists – CREATE_ALWAYS — An existing file will be overwritten – OPEN_EXISTING — Fail if the file does not exist – OPEN_ALWAYS — Open the file or create it if it doesn’t exist – TRUNCATE_EXISTING — File length will be set to zero Note: There is no “open to append” mode – You will need to position to the end of file

27 CREATING AND OPENING FILES dwAttrsAndFlags — 16 flags and attributes including: – FILE_ATTRIBUTE_NORMAL — No other attributes are set – FILE_ATTRIBUTE_READONLY — Cannot write or delete – FILE_FLAG_OVERLAPPED – FILE_FLAG_SEQUENTIAL_SCAN and FILE_FLAG_RANDOM_ACCESS provide performance hints Attributes are properties of the files themselves Flags are associated with a specific HANDLE – Different HANDLE s to the same file can have different flags ● Example: One HANDLE is “overlapped,” another not ● Or, one has FILE_FLAG_SEQUENTIAL_SCAN and another FILE_FLAG_RANDOM_ACCESS

28 CREATING AND OPENING FILES File processing flags include: – FILE_FLAG_WRITE_THROUGH – FILE_FLAG_NO_BUFFERING – FILE_FLAG_DELETE_ON_CLOSE hTemplateFile — Handle of an open GENERIC_READ file – Use the same attributes for the new file

29 ReadFile BOOL ReadFile (HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped) Return: TRUE if the read succeeds ● Even if no bytes were read due to an attempt to read past the end of file ● FALSE indicates an invalid handle, a handle without GENERIC_READ access, etc.

30 ReadFile Parameters hFile — File handle with GENERIC_READ access lpBuffer — Me m ory buffer to receive the input data nNumberOfBytesToRead ● Number of bytes you expect to read * lpNumberOfBytesRead ● Actual number of bytes transferred ● Zero indicates end of file lpOverlapped ● Points to OVERLAPPED structure ( NULL for now)

31 WriteFile BOOL WriteFile ( HANDLE hFile, CONST VOID *lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped) Return: TRUE if the function succeeds; FALSE otherwise

32 CloseHandle BOOL CloseHandle (HANDLE hObject) Return: TRUE if the function succeeds; FALSE otherwise This function is general purpose and will be used to close handles to many different object types

33 CopyFile BOOL CopyFile (LPCTSTR lpExistingFile, LPCTSTR lpNewFile, BOOL fFailIfExists) If a file with the new name already exists, it will be replaced only if fFailIfExists is FALSE This is a “convenience function” and also provides performance

34 SetFilePointer DWORD SetFilePointer( HANDLE hFile, LONG lDistanceToMove, PLONG lpDistanceToMoveHigh, DWORD dwMoveMethod ); Parameters hFile [in] A handle to the file that has a file pointer to be moved. The file handle must be created with the GENERIC_READ or GENERIC_WRITE access right.

35 SetFilePointer lpDistanceToMoveHigh [in, out, optional] A pointer to the high order 32-bits of the signed 64-bit distance to move. If you do not need the high order 32-bits, this pointer must be set to NULL. When not NULL, this parameter also receives the high order DWORD of the new value of the file pointer. dwMoveMethod [in] The starting point for the file pointer move. This parameter can be one of the following values. Value Meaning FILE_BEGIN The starting point is 0 (zero) or the beginning of the file. FILE_CURRENT The starting point is the current value of the file pointer. FILE_END The starting point is the current end-of-file position.

36 SetFilePointer Return Values If the SetFilePointer function succeeds and lpDistanceToMoveHigh is NULL, the return value is the low order DWORD of the new file pointer. If lpDistanceToMoveHigh is not NULL, the function returns the low order DWORD of the new file pointer, and puts the high order DWORD of the new file pointer into the LONG pointed to by that parameter. If the function fails and lpDistanceToMoveHigh is NULL, the return value is INVALID_SET_FILE_POINTER. If the function fails, and lpDistanceToMoveHigh is not NULL, the return value is INVALID_SET_FILE_POINTER. However, because INVALID_SET_FILE_POINTER is a valid value for the low order DWORD of the new file pointer, you must check GetLastError to determine whether or not an error occurred. If an error occurred, GetLastError returns a value different from NO_ERROR. For a code example that shows you this scenario, see the Remarks section in this topic. If a new file pointer is a negative value, the function fails, the file pointer is not moved, and the code returned by GetLastError is ERROR_NEGATIVE_SEEK.

37 Win32 Examples ● who1.c ● who2.c ● who3.c ● more01.c ● more02.c ● cp1.c ● utmplib.c ● cpC.c ● cpCF.c ● cpU.c ● cpUC.c ● cpW.c ● cpWFA.c Examples

38 Unix Warmup Ssh -Y poseidon.cs.kent.edu emacs ~/bin (k)hexedit a.out double * ys; memcpy(ys,xs,size); ys+=size; Inode df du

39 Directories, File info The shell command ls provides information on a file's size, ownership, group, type The shell command stat (on Linux systems) provides, in addition, device types, uid, gid, inode access, modify, and change times How does the program get this information?

40 File System Organization

41 What is a directory? It is a special kind of file that contains a list of files and/or other directories. Every directory contains the itesm “.” and “..” opendir(name)-Opens a directory stream. Returns a DIR *. readdir(DIR *)-gets next record for directory and returns a struct dirent *. closedir(DIR *)-close the directory stream.

42 struct dirent { long d_ino; /* inode number */ off_t d_off; /* offset to this dirent */ unsigned short d_reclen; /* length of this d_name */ char d_name [NAME_MAX+1]; /* file name (null-terminated) */ }

43 Sample Code / ** ls1.c ** purpose list contents of directory or directories ** action if no args, use. else list files in args **/ #include void do_ls(char []); main(int ac, char *av[]) { if ( ac == 1 ) do_ls( "." ); else while ( --ac ){ printf("%s:\n", *++av ); do_ls( *av ); }

44 Sample Code void do_ls( char dirname[] ) /* * list files in directory called dirname */ { DIR *dir_ptr; /* the directory */ struct dirent *direntp; /* each entry */ if ( ( dir_ptr = opendir( dirname ) ) == NULL ) fprintf(stderr,"ls1: cannot open %s\n", dirname); else { while ( ( direntp = readdir( dir_ptr ) ) != NULL ) printf("%s\n", direntp->d_name ); closedir(dir_ptr); }

45 Reading Inodes Data The information about a file is stored in an inode. When the file system is created, a table of inodes is created to store file information. A directory only contains the name of a file and the files inode number. To find out the size, type, owner, etc of a file we need to access its inode with the system call stat.

46 stat NAME stat, fstat, lstat - get file status SYNOPSIS #include int stat(const char *file_name, struct stat *buf); int fstat(int filedes, struct stat *buf); int lstat(const char *file_name, struct stat *buf);

47 Stat DESCRIPTION These functions return information about the specified file. You do not need any access rights to the file to get this information but you need search rights to all directories named in the path leading to the file. stat stats the file pointed to by file_name and fills in buf. lstat is identical to stat, except in the case of a symbolic link, where the link itself is stat-ed, not the file that it refers to. fstat is identical to stat, only the open file pointed to by filedes (as returned by open(2)) is stat-ed in place of file_name.

48 Stat They all return a stat structure, which contains the following fields: struct stat { dev_t st_dev; /* device */ ino_t st_ino; /* inode */ mode_t st_mode; /* protection */ nlink_t st_nlink; /* number of hard links */ uid_t st_uid; /* user ID of owner */ gid_t st_gid; /* group ID of owner */ dev_t st_rdev; /* device type (if inode device) */ off_t st_size; /* total size, in bytes */ blksize_t st_blksize; /* blocksize for filesystem I/O */ blkcnt_t st_blocks; /* number of blocks allocated */ time_t st_atime; /* time of last access */ time_t st_mtime; /* time of last modification */ time_t st_ctime; /* time of last status change */ };

49 fileinfo.c #include void show_stat_info(char *, struct stat *); int main(int ac, char *av[]) {struct stat info; /* buffer for file info */ if (ac>1) if( stat(av[1], &info) != -1 ){ show_stat_info( av[1], &info ); return 0; } else perror(av[1]); /* report stat() errors */ return 1; }

50 fileinof.c void show_stat_info(char *fname, struct stat *buf) {printf(" mode: %o\n", buf->st_mode); /* type + mode */ printf(" links: %d\n", buf->st_nlink);/* # links */ printf(" user: %d\n", buf->st_uid); /* user id */ printf(" group: %d\n", buf->st_gid); /* group id */ printf(" size: %d\n", buf->st_size); /* file size */ printf("modtime: %d\n", buf->st_mtime);/* modified */ printf(" name: %s\n", fname ); /* filename */ }

51 mode number 1 0 0 0 0 0 0 1 1 0 1 0 0 1 0 0 -rw-rw-r--

52 umask UMASK(2) Linux Programmer's Manual UMASK(2) NAME umask - set file creation mask SYNOPSIS #include mode_t umask(mode_t mask); DESCRIPTION umask sets the umask to mask & 0777. The umask is used by open(2) to set initial file permissions on a newly-created file. Specifically, permissions in the umask are turned off from the mode argument to open(2) (so, for example, the common umask default value of 022 results in new files being created with per- missions 0666 & ~022 = 0644 = rw-r--r-- in the usual case where the mode is specified as 0666).

53 Using Masks Stat constants #define S_IFMT 0170000 /* bitmask for the file type bitfields*/ #define S_IFSOCK 0140000 /*socket*/ Stat macros: #define S_ISFIFO(m) (((m) & 0170000)) == (0010000)) Macros and constants listed in man pages

54 Masks S_IFMT 0170000 bitmask for the file type bitfields S_IFSOCK 0140000 socket S_IFLNK 0120000 symbolic link S_IFREG 0100000 regular file S_IFBLK 0060000 block device S_IFDIR 0040000 directory S_IFCHR 0020000 character device S_IFIFO 0010000 fifo

55 Masks S_ISUID 0004000 set UID bit S_ISGID 0002000 set GID bit (see below) S_ISVTX 0001000 sticky bit (see below) S_IRWXU 00700 mask for file owner permissions S_IRUSR 00400 owner has read permission S_IWUSR 00200 owner has write permission S_IXUSR 00100 owner has execute permission S_IRWXG 00070 mask for group permissions S_IRGRP 00040 group has read permission S_IWGRP 00020 group has write permission S_IXGRP 00010 group has execute permission S_IRWXO 00007 mask for permissions for others (not in group) S_IROTH 00004 others have read permission

56 Setting mode bits The mode bits can be set with open: fid = open(filestr, O_CREAT|O_WRONLY|O_TRUNC, S_IRWXU|S_IRGRP|S_IROTH) In a shell, one can use chmod: chmod u+rwx,g+r,o+r myfile

57 getpwuid struct passwd *getpwuid(uid_t uid); struct passwd *getpwnam(const char *name); struct passwd { char *pw_name; /* user name */ char *pw_passwd; /* user password */ uid_t pw_uid; /* user id */ gid_t pw_gid; /* group id */ char *pw_gecos; /* real name */ char *pw_dir; /* home directory */ char *pw_shell; /* shell program */ };

58 getgrgid struct group *getgrnam(const char *name); struct group *getgrgid(gid_t gid); struct group { char *gr_name; /* group name */ char *gr_passwd; /* group password */ gid_t gr_gid; /* group id */ char **gr_mem; /* group members */ }; Note: a users can be in more than one group.

59 Set UID and Set GID bits For executable files if these bits are set, the the process will run with the user and/or group permissions of the owner of the file rather than the user that started the process The set GID bit (S_ISGID) has several special uses: For a directory it indicates that BSD semantics is to be used for that directory: files created there inherit their group ID from the directory, not from the effective gid of the creating process, and directories created there will also get the S_ISGID bit set. For a file that does not have the group execution bit (S_IXGRP) set, it indicates mandatory file/record locking. The 'sticky' bit (S_ISVTX) on a directory means that a file in that directory can be renamed or deleted only by the owner of the file, by the owner of the directory, and by root.

60 links stat reports the the number of links associated with an object. What is that? When a file is added to a directory, a link is established. When it is removed its link to that directory is removed. A file can be linked to any number of different directories and have any number of different names in a directory. The shell commands link and ln and the system call link will create links between files in the same file system. To link files in different file systesm use a symbolic (ln -s, symlink) link.

61 Modification and Access Times Modify: The last time the file was written to Access: The last time the file was read Change: The last time the permission bits were changed. One can change the Access and Modify times with utime and touch.

62 Ownership and Group The shell command and system command chown can change the ownership of a file The shell command chgrp and system command chown can change the group of a file.

63 Exercise Recursive ls. Standard ls supports the -R option. This option lists the contents of a directory and the contents of all directories below it. Modify ls2.c to support the -R option. Windows program will need to use GetFileAttributes.

64 C issues C Question: What does strutptr= (struct mystrct *) malloc(nstructs * sizeof(struct mystrct)); do?

65 safe_read size_t safe_read(int fd, void *buf, size_t count) { size_t n; do { n = read(fd, buf, count); } while (n < 0 && errno == EINTR); return n; }

66 Windows:UNICODE & GENERIC CHARACTERS Windows NT supports 16-bit characters WCHAR or wchar_t To assure maximum flexibility and source portability, define all characters and strings using “generic” type TCHAR Calculate lengths using sizeof(TCHAR) Include #define UNICODE (to get WCHAR ) in all source modules (or #undef UNICODE to get CHAR ) Define UNICODE before #include Also define _ UNICODE consistently for the generic C library library

67 Unicode Strings Constant strings in one of three forms (first 2 are ANSI C) The last is a macro "This string uses 8-bit characters" L"This string uses 16-bit characters" _T ("This string uses generic characters") Expands to “T…” if UNICODE is not defined; L”T…” if it is TEXT macro is the same as _T LPTSTR expands to either char * or wchar_t *

68 _? TEXT vs. _TEXT vs. _T, and UNICODE vs. _UNICODE The plain versions without the underscore affect the character set the Windows header files treat as default. So if you define UNICODE, then GetWindowText will map to GetWindowTextW instead of GetWindowTextA, for example. Similarly, the TEXT macro will map to L"..." instead of "...". The versions with the underscore affect the character set the C runtime header files treat as default. So if you define _UNICODE, then _tcslen will map to wcslen instead of strlen, for example. Similarly, the _TEXT macro will map to L"..." instead of "...".

69 C runtime library Define _UNICODE consistently with UNICODE This makes available a wide class of string processing and I/O functions _fgettc, _itot, _ttoi, _totupper, _totlower And many more — nearly the complete library Also, locale-specific functions (language specific) (seven in all): lstrlen, lstrcmp, lstrcpy, lstrcat, … Be sure to #include after Note: Any _ keyword or function is specific to Microsoft Visual C++ and the Microsoft compiler

70 Main Program Windows main is for ASCII; wmain is for Unicode In place of int main (argc, char * argv[]) or int main (argc, w_char * argv[]) Use #include /* this is after */... int _tmain (int argc, LPTSTR argv[]) The _tmain macro then expands to main or wmain Depending on definition of _UNICODE This assures correct operation in all circumstances and combinations

71 FILE AND DIRECTORY MANAGEMENT BOOL DeleteFile (LPCTSTR lpFileName) You cannot delete an open file in Windows NT (You can in Windows 9x)

72 FILE AND DIRECTORY MANAGEMENT Renaming Files BOOL MoveFile (LPCTSTR lpExisting, LPCTSTR lpNew) Source and target files must be on the same drive. Fails if file lpNew exists. BOOL MoveFileEx (LPCTSTR lpExisting, LPCTSTR lpNew, DWORD dwFlags) Source and target files can be on different drives. Succeeds if lpNew exists. Note: There are no soft links as in UNIX Shortcuts are not the same thing; they are only recognized by the visual shell

73 Renaming Parameters lpExisting — The name of the existing file or directory lpNew — Cannot exist with MoveFile Directories must be on same file system. If NULL the existing file is deleted dwFlags MOVEFILE_REPLACE_EXISTING To replace an existing file MOVEFILE_COPY_ALLOWED Copy then delete

74 Directories BOOL CreateDirectory (LPCTSTR lpPath, LPSECURITY_ATTRIBUTES lpsa) BOOL RemoveDirectory (LPCTSTR lpPath) lpPath Points to a null-terminated string with the directory name

75 Directories BOOL SetCurrentDirectory (LPCTSTR lpCurDir) lpCurDir The path to the new current directory There is actually a current directory maintained for each drive SetCurrentDirectory (TEXT("C:")); Will set the C: drive directory to its current value

76 Directories DWORD GetCurrentDirectory (DWORD nBufferLength, LPTSTR lpBuffer) Return: The string length of the returned pathname The required buffer size if the buffer is not large enough This includes the space for the null string terminator Zero if the function fails

77 Directories HANDLE FindFirstFile (LPCTSTR lpFilename,, LPWIN32_FIND_DATA lpffd); Return: A search handle. INVALID_HANDLE_VALUE indicates failure. FindFirstFile examines both subdirectory and filenames, looking for a Name match (could be "*"). The returned handle is used in subsequent searches. t ypedef struct _WIN32_FIND_DATA { DWORD dwFileAttributes; FILETIME ftCreationTime; FILETIME ftLastAccessTime; FILETIME ftLastWriteTime; DWORD nFileSizeHigh; DWORD nFileSizeLow; DWORD dwReserved0; DWORD dwReserved1; TCHAR cFileName[ MAX_PATH ]; TCHAR cAlternateFileName[ 14 ]; } WIN32_FIND_DATA,*PWIN32_FIND_DATA, *LPWIN32_FIND_DATA;

78 Directories BOOL FindNextFile (HANDLE hFindFile,, LPWIN32_FIND_DATA lpffd); Return: FALSE in cases of invalid arguments or if no more matching files can be found, in which cass the GetLastError will return ERROR_NO_MORE_FILES.

79 Directories BOOL FindClose (HANDLE hFindFile,LPWIN32_FIND_DATA lpffd);

80 PWD /* cl -DWIN32 PWD.C PRINTMSG.C REPRTERR.C */ #include "EvryThng.h" #define DIRNAME_LEN MAX_PATH + 2 int _tmain (int argc, LPTSTR argv []) { /* Buffer to receive current directory allows for the CR, LF at the end of the longest possible path. */ TCHAR pwdBuffer [DIRNAME_LEN]; DWORD LenCurDir; LenCurDir = GetCurrentDirectory (DIRNAME_LEN, pwdBuffer); if (LenCurDir == 0) ReportError (_T ("Failure getting pathname."), 1, TRUE); if (LenCurDir > DIRNAME_LEN) ReportError (_T ("Pathname is too long."), 2, FALSE); PrintMsg (GetStdHandle (STD_OUTPUT_HANDLE), pwdBuffer); return 0; }


Download ppt "Files ● System Calls and Functions – Unix: open, read,write,creat, lseek,close – Win32: CreateFile, CloseHandle, ReadFile, WriteFile, SetFilePointer ●"

Similar presentations


Ads by Google