84
JMH Associates © 2004, All rights reserved Chapters 2-3 Chapters 2-3 Input/Output With File and Directory Processing

1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

  • View
    214

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

1JMH Associates © 2004, All rights reserved

Chapters 2-3Chapters 2-3Chapters 2-3Chapters 2-3

Input/Output

With File and Directory Processing

Page 2: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

2JMH Associates © 2004, All rights reserved

OBJECTIVES (1 of 2)OBJECTIVES (1 of 2)OBJECTIVES (1 of 2)OBJECTIVES (1 of 2)

Upon completion of this Chapter you will be able to: Describe the Windows file systems Perform sequential file processing Perform console I/O and direct access file I/O Report and analyze system call errors Describe and use Unicode characters and strings and write

generic applications (both Unicode and ASCII characters) Use Windows mandatory file locking to protect files from

concurrent modification by several processes Perform file and directory management

Page 3: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

3JMH Associates © 2004, All rights reserved

OBJECTIVES (2 of 2)OBJECTIVES (2 of 2)OBJECTIVES (2 of 2)OBJECTIVES (2 of 2)

You will also be prepared for later Chapters Memory-mapped files Process management Interprocess communication Threads Synchronization Asynchronous I/O

Page 4: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

4JMH Associates © 2004, All rights reserved

AGENDAAGENDAAGENDAAGENDA

Part I File Systems and Sequential I/O

Part II Unicode and Generic Characters

Part III Console I/O

Part IV Lab 2–A

Part V Direct File Access

Part VI File Locking

Part VII File and Directory ManagementLab 3–B

Page 5: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

5JMH Associates © 2004, All rights reserved

Part IPart IPart IPart I

File Systems and Sequential I/O

Page 6: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

6JMH Associates © 2004, All rights reserved

BASIC I/OBASIC I/OBASIC I/OBASIC I/O

Basic Windows API file processing functions:

CreateFile

ReadFile

WriteFile

CloseHandle

We used these, in a very simple program, in Chapter 1

Page 7: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

7JMH Associates © 2004, All rights reserved

THE FILE SYSTEMSTHE FILE SYSTEMSTHE FILE SYSTEMSTHE FILE SYSTEMS

Windows File Systems (Virtual) File Allocation Table File System (FAT, VFAT)

The only disk file system for floppies and Windows 9x NTFS File System (NTFS)

Very large (“huge”) files, secure, robust Supported on Windows NT (all versions)

CD-ROM File System (CDFS) Custom file systems

Developed by software vendors

Page 8: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

8JMH Associates © 2004, All rights reserved

Windows FILE NAMING (1 of 2)Windows FILE NAMING (1 of 2)Windows FILE NAMING (1 of 2)Windows FILE NAMING (1 of 2)

Hierarchical

Full pathname can start with a drive name A:, C:, … Or with a “share” name

\\servername\sharename

Pathname separator is a backslash — \ You can also use / in C

Page 9: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

9JMH Associates © 2004, All rights reserved

Windows FILE NAMING (2 of 2)Windows FILE NAMING (2 of 2)Windows FILE NAMING (2 of 2)Windows FILE NAMING (2 of 2)

Directory and file names cannot use ASCII 1–31 Or any of   < > : " | But you can have blanks in file names

Case insensitive but case retaining

File, directory names up to 255 characters long 250 in Windows 9x

A period . separates a file’s name from its extension The period is in the name; there can be more than one

. and .. indicate the current directory and its parent

Page 10: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

10JMH Associates © 2004, All rights reserved

CREATING AND OPENING FILESCREATING AND OPENING FILESCREATING AND OPENING FILESCREATING AND OPENING FILES

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 in Part II

Page 11: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

11JMH Associates © 2004, All rights reserved

CREATING AND OPENING FILESCREATING AND OPENING FILES(2 OF 6)(2 OF 6)

CREATING AND OPENING FILESCREATING AND OPENING FILES(2 OF 6)(2 OF 6)

Parameters

lpName Pointer to the string naming the file Length normally limited to 260 \\?\ is an escape prefix allowing long NT path names

dwAccess Access using GENERIC_READ or GENERIC_WRITE Note: Flags can be combined with |

Page 12: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

12JMH Associates © 2004, All rights reserved

CREATING AND OPENING (3 OF 6)CREATING AND OPENING (3 OF 6)CREATING AND OPENING (3 OF 6)CREATING AND OPENING (3 OF 6)

dwShareMode 0 — Cannot be shared; not even this process can open

another handle FILE_SHARE_READ — Other processes can read

concurrently FILE_SHARE_WRITE — Other processes can write

concurrently

lpsa points to a SECURITY_ATTRIBUTES structure NULL for now

Page 13: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

13JMH Associates © 2004, All rights reserved

CREATING AND OPENING (4 OF 6)CREATING AND OPENING (4 OF 6)CREATING AND OPENING (4 OF 6)CREATING AND OPENING (4 OF 6)

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

Page 14: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

14JMH Associates © 2004, All rights reserved

CREATING AND OPENING (5 OF 6)CREATING AND OPENING (5 OF 6)CREATING AND OPENING (5 OF 6)CREATING AND OPENING (5 OF 6)

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 themselvesFlags are associated with a specific HANDLE

Different HANDLEs 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

Page 15: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

15JMH Associates © 2004, All rights reserved

CREATING AND OPENING (6 OF 6)CREATING AND OPENING (6 OF 6)CREATING AND OPENING (6 OF 6)CREATING AND OPENING (6 OF 6)

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

Page 16: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

16JMH Associates © 2004, All rights reserved

READING FILES (1 OF 2)READING FILES (1 OF 2)READING FILES (1 OF 2)READING FILES (1 OF 2)

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.

Page 17: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

17JMH Associates © 2004, All rights reserved

READING FILES (2 OF 2)READING FILES (2 OF 2)READING FILES (2 OF 2)READING FILES (2 OF 2)

Parameters

hFile — File handle with GENERIC_READ access

lpBuffer — Memory 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)

Page 18: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

18JMH Associates © 2004, All rights reserved

WRITING FILESWRITING FILESWRITING FILESWRITING FILES

BOOL WriteFile (HANDLE hFile, CONST VOID *lpBuffer,DWORD nNumberOfBytesToWrite,LPDWORD lpNumberOfBytesWritten,LPOVERLAPPED lpOverlapped)

Return: TRUE if the function succeeds; FALSE otherwise

Page 19: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

19JMH Associates © 2004, All rights reserved

CLOSING FILESCLOSING FILESCLOSING FILESCLOSING FILES

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

Page 20: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

20JMH Associates © 2004, All rights reserved

COPYING FILESCOPYING FILESCOPYING FILESCOPYING FILES

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

Page 21: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

21JMH Associates © 2004, All rights reserved

Part IIPart IIPart IIPart II

Unicode and Generic Characters

Page 22: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

22JMH Associates © 2004, All rights reserved

UNICODE & GENERIC CHARACTERSUNICODE & GENERIC CHARACTERSUNICODE & GENERIC CHARACTERSUNICODE & 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” typeTCHAR

Calculate lengths using sizeof(TCHAR) Include #define UNICODE (to get WCHAR) in all source

modules (or #undef UNICODE to get CHAR) Be consistent Define UNICODE before #include <windows.h>

Also define _UNICODE consistently for the generic C library

Page 23: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

23JMH Associates © 2004, All rights reserved

GENERIC CHARACTERS (2 of 3)GENERIC CHARACTERS (2 of 3)GENERIC CHARACTERS (2 of 3)GENERIC CHARACTERS (2 of 3)

Use the “generic” C library for all string functions _tprintf in place of printf _stprintf in place of sprintf _tcslen in place of strlen _itot in place of itoa

And MANY more See the on line help and the lab programs

Generic versions of some functions are not provided e.g. memchr - Replacements are in the lab solutions

Page 24: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

24JMH Associates © 2004, All rights reserved

GENERIC CHARACTERS (3 of 3)GENERIC CHARACTERS (3 of 3)GENERIC CHARACTERS (3 of 3)GENERIC CHARACTERS (3 of 3)

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 *

Page 25: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

25JMH Associates © 2004, All rights reserved

THE GENERIC C LIBRARYTHE GENERIC C LIBRARYTHE GENERIC C LIBRARYTHE GENERIC C 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 (seven in all):

lstrlen, lstrcmp, lstrcpy, lstrcat, … Be sure to #include <tchar.h> after <windows.h>

Note: Any _ keyword or function is specific to Microsoft Visual C++ and the Microsoft compiler

Page 26: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

26JMH Associates © 2004, All rights reserved

GENERIC CHARACTERS AND THE GENERIC CHARACTERS AND THE MAIN PROGRAMMAIN PROGRAM

GENERIC CHARACTERS AND THE GENERIC CHARACTERS AND THE MAIN PROGRAMMAIN 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 <tchar.h>

/* this is after <windows.h> */

... 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

Page 27: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

27JMH Associates © 2004, All rights reserved

Part IIIPart IIIPart IIIPart III

Standard Devices and Console I/O

Page 28: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

28JMH Associates © 2004, All rights reserved

STANDARD DEVICESSTANDARD DEVICESAND CONSOLE I/O (1 of 7)AND CONSOLE I/O (1 of 7)

STANDARD DEVICESSTANDARD DEVICESAND CONSOLE I/O (1 of 7)AND CONSOLE I/O (1 of 7)

HANDLE GetStdHandle (DWORD dwDevice)

Return: A valid handle or INVALID_HANDLE_VALUE for failure

BOOL SetStdHandle (DWORD IDStdHandle,

HANDLE hHandle)

Return: TRUE or FALSE indicating success or failure

Page 29: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

29JMH Associates © 2004, All rights reserved

STANDARD DEVICESSTANDARD DEVICESAND CONSOLE I/O (2 of 7)AND CONSOLE I/O (2 of 7)

STANDARD DEVICESSTANDARD DEVICESAND CONSOLE I/O (2 of 7)AND CONSOLE I/O (2 of 7)

dwDevice and IDStdHandle Must have one of these values:

STD_INPUT_HANDLE STD_OUTPUT_HANDLE STD_ERROR_HANDLE

Page 30: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

30JMH Associates © 2004, All rights reserved

STANDARD DEVICESSTANDARD DEVICESAND CONSOLE I/O (3 of 7)AND CONSOLE I/O (3 of 7)

STANDARD DEVICESSTANDARD DEVICESAND CONSOLE I/O (3 of 7)AND CONSOLE I/O (3 of 7)

hHandle Specifies an open file that is to be the standard device

Two reserved pathnames for console input (the keyboard):

"CONIN$"

and output (the display):

"CONOUT"

Page 31: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

31JMH Associates © 2004, All rights reserved

STANDARD DEVICESSTANDARD DEVICESAND CONSOLE I/O (4 of 7)AND CONSOLE I/O (4 of 7)

STANDARD DEVICESSTANDARD DEVICESAND CONSOLE I/O (4 of 7)AND CONSOLE I/O (4 of 7)

BOOL SetConsoleMode (HANDLE hConsole,

DWORD fdevMode)

Return: TRUE if and only if the function succeeds

hConsole Must have GENERIC_WRITE access

Page 32: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

32JMH Associates © 2004, All rights reserved

STANDARD DEVICESSTANDARD DEVICESAND CONSOLE I/O (5 of 7)AND CONSOLE I/O (5 of 7)

STANDARD DEVICESSTANDARD DEVICESAND CONSOLE I/O (5 of 7)AND CONSOLE I/O (5 of 7)

fDevMode — How characters are processed ENABLE_WINDOW_INPUT ENABLE_LINE_INPUT ENABLE_ECHO_INPUT ENABLE_PROCESSED_INPUT ENABLE_PROCESSED_OUTPUT ENABLE_WRAP_AT_EOL_OUTPUT

Page 33: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

33JMH Associates © 2004, All rights reserved

STANDARD DEVICESSTANDARD DEVICESAND CONSOLE I/O (6 of 7)AND CONSOLE I/O (6 of 7)

STANDARD DEVICESSTANDARD DEVICESAND CONSOLE I/O (6 of 7)AND CONSOLE I/O (6 of 7)

BOOL ReadConsole (HANDLE hConsoleInput,LPVOID lpvBuffer, DWORD cchToRead,LPDWORD lpcchRead, LPVOID lpvReserved)

Return: TRUE if and only if the read succeeds

Page 34: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

34JMH Associates © 2004, All rights reserved

STANDARD DEVICESSTANDARD DEVICESAND CONSOLE I/O (7 of 7)AND CONSOLE I/O (7 of 7)

STANDARD DEVICESSTANDARD DEVICESAND CONSOLE I/O (7 of 7)AND CONSOLE I/O (7 of 7)

BOOL WriteConsole Same as ReadConsole

BOOL FreeConsole (VOID)

BOOL AllocConsole (VOID)

Page 35: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

35JMH Associates © 2004, All rights reserved

EXAMPLE: EXAMPLE: PrintStringsPrintStrings (1 of 3) (1 of 3)EXAMPLE: EXAMPLE: PrintStringsPrintStrings (1 of 3) (1 of 3)

#include "envirmnt.h" /* UNICODE is defined here */#include <windows.h>

BOOL PrintStrings (HANDLE hOut, ...)

/* Write the messages to the output handle (hOut) Use WriteConsole (to handle Unicode & console processing) first, as the output will normally be the console. If that fails, use WriteFile.

hOut: Handle for output file. ... : Variable argument list containing TCHAR strings. The list must be terminated with NULL. */

Page 36: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

36JMH Associates © 2004, All rights reserved

PrintStringsPrintStrings (2 of 3) (2 of 3)PrintStringsPrintStrings (2 of 3) (2 of 3)

{ DWORD MsgLen, Count; BOOL Success = TRUE; LPCTSTR pMsg; va_list pMsgList; /* Current message string */ va_start (pMsgList, hOut);

/* Start processing msgs */ while (((pMsg = va_arg (pMsgList, LPCTSTR)) != NULL) && Success) { MsgLen = _tcslen (pMsg);

(CONTINUED)

Page 37: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

37JMH Associates © 2004, All rights reserved

PrintStringsPrintStrings (3 of 3) (3 of 3)PrintStringsPrintStrings (3 of 3) (3 of 3)

/* WriteConsole fails if the handle is associated with a file rather than with a console */

if ( !WriteConsole (hOut, pMsg, MsgLen, &Count, NULL) &&

!WriteFile (hOut, pMsg,

MsgLen * sizeof (TCHAR), &Count, NULL))

return FALSE; } /* End of while loop - process next message */ va_end (pMsgList); return TRUE;}

Page 38: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

38JMH Associates © 2004, All rights reserved

EXAMPLE: EXAMPLE: ReportErrorReportError (1 of 4) (1 of 4)EXAMPLE: EXAMPLE: ReportErrorReportError (1 of 4) (1 of 4)

OBJECTIVE: Turn system call errors into meaningful text strings

And print the text Terminate the program if the error is fatal

Similar to perror(), but it works in the multithreaded Windows environment.

Page 39: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

39JMH Associates © 2004, All rights reserved

EXAMPLE: EXAMPLE: ReportErrorReportError (2 of 4) (2 of 4)EXAMPLE: EXAMPLE: ReportErrorReportError (2 of 4) (2 of 4)

#include "envirmnt.h"#include <windows.h>#include "support.h"

VOID ReportError (LPCTSTR UserMessage, DWORD ExitCode, BOOL PrintErrorMsg)/* General-purpose function to report system errors. Obtain the error number and turn it into the system error message. Display this information and the user specified message to the standard error device. UserMessage: Message to be displayed to standard error device. */

Page 40: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

40JMH Associates © 2004, All rights reserved

ReportErrorReportError (3 of 4) (3 of 4)ReportErrorReportError (3 of 4) (3 of 4)

ExitCode: 0 - Return > 0 - ExitProcess with this code PrintErrorMessage: Display the last system error message if this flag is set. */{ DWORD eMsgLen, ErrNum = GetLastError (); LPVOID lpvSysMsg; HANDLE hStdErr = GetStdHandle (STD_ERROR_HANDLE); PrintMsg (hStdErr, UserMessage); if (PrintErrorMsg) {

Page 41: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

41JMH Associates © 2004, All rights reserved

ReportErrorReportError (4 of 4) (4 of 4)ReportErrorReportError (4 of 4) (4 of 4)

eMsgLen = FormatMessage ( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, ErrNum, MAKELANGID (LANG_DFLT, SUBLANG_DFLT), &lpvSysMsg, 0, NULL); PrintStrings (hStdErr, TEXT ("\n"), lpvSysMsg, TEXT ("\n"), NULL); HeapFree (GetProcessHeap (), 0, lpvSysMsg);

}if (ExitCode > 0)

ExitProcess (ExitCode);else

return;}

Page 42: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

42JMH Associates © 2004, All rights reserved

LAB 2–A (Option 1)LAB 2–A (Option 1)LAB 2–A (Option 1)LAB 2–A (Option 1)

Modify the copy program in Chapter 1 to create the program cpCF which will:

Take the input and output files from the command line Use the generic macro _tmain Report all system errors using ReportError () Use the CopyFile function Prompt the user to see if an existing file should be

overwritten.

Page 43: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

43JMH Associates © 2004, All rights reserved

LAB 2–A (Option 2)LAB 2–A (Option 2)LAB 2–A (Option 2)LAB 2–A (Option 2)

Create a program, atou, which behaves just like cp except that the input file is assumed to be in ASCII and the output file will be the Unicode equivalent (and twice as long as the original). Include the asc2un.c source file in your project.

We will build several variations of this program during the course to illustrate different file processing techniques.

Page 44: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

44JMH Associates © 2004, All rights reserved

LAB 2–A (Option 3)LAB 2–A (Option 3)LAB 2–A (Option 3)LAB 2–A (Option 3)

Create a program, cat, that takes multiple file names from the command line and copies them, in order, to standard output. If there are no file names on the command line, use standard input.

This program will be required with several future labs.

Addtional Note: You will find it convenient to put your working programs (.EXE files) in a common directory, such as RUN (Provided with the solutions).

Page 45: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

45JMH Associates © 2004, All rights reserved

Part VPart VPart VPart V

Direct File Access

Page 46: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

46JMH Associates © 2004, All rights reserved

FILE POINTERS (1 of 4)FILE POINTERS (1 of 4)FILE POINTERS (1 of 4)FILE POINTERS (1 of 4)

DWORD SetFilePointer (HANDLE hFile,LONG lDistanceToMove,PLONG lpDistanceToMoveHigh,DWORD dwMoveMethod)

Return: The low-order DWORD (unsigned) of the new file pointer. The high-order portion of the new file pointer goes to the DWORD indicated by lpDistanceToMoveHigh (if non-NULL). In case of error, the return value is OxFFFFFFFF.

Note: The file pointer is associated with the HANDLE, not the file. The pointer advances with each read and write.

Page 47: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

47JMH Associates © 2004, All rights reserved

FILE POINTERS (2 of 4)FILE POINTERS (2 of 4)FILE POINTERS (2 of 4)FILE POINTERS (2 of 4)

Note: NTFS is a 64-bit file system, so file pointers are 64 bits long. The file pointer is specified with two 32-bit parts.

Large files are increasingly important in many applications But many users will only require “short” (< 4GB) files

SetFilePointer Parameters

hFile — Handle of an open file with read and/or write access

lDistanceToMove — LONG signed distance to move or unsigned file position

Page 48: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

48JMH Associates © 2004, All rights reserved

FILE POINTERS (3 of 4)FILE POINTERS (3 of 4)FILE POINTERS (3 of 4)FILE POINTERS (3 of 4)

*lpDistanceToMoveHigh High-order portion of the move distance Can be NULL for “small” files

dwMoveMethod — Specifies one of these modes: FILE_BEGIN — Position from the start of file FILE_CURRENT — Move pointer forward or backward FILE_END — Position backward from end of file

SetEndOfFile () function resizes the file based on the current file pointer

Page 49: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

49JMH Associates © 2004, All rights reserved

FILE POINTERS (4 of 4)FILE POINTERS (4 of 4)FILE POINTERS (4 of 4)FILE POINTERS (4 of 4)

Use the LARGE_INTEGER data type (union) for 64-bit file positions

Example coming up

Members: LONGLONG Quadpart Do the 64-bit arithmetic hereDWORD LowPartLONG HighPart

Page 50: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

50JMH Associates © 2004, All rights reserved

Alternative Direct File Access Using Alternative Direct File Access Using the Overlapped Structure (1 of 2)the Overlapped Structure (1 of 2)

Alternative Direct File Access Using Alternative Direct File Access Using the Overlapped Structure (1 of 2)the Overlapped Structure (1 of 2)

Example: Use the Offset fields in the overlapped structure Offset Low order 32 bits OffsetHigh High order 32 bits hEvent Must be NULL. This field is

used with asynchronous I/O

Two reserved fields Do not use!!

The example shows how to update a record in a file

Page 51: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

51JMH Associates © 2004, All rights reserved

Alternative Direct File Access Using Alternative Direct File Access Using the Overlapped Structure (2 of 2)the Overlapped Structure (2 of 2)

Alternative Direct File Access Using Alternative Direct File Access Using the Overlapped Structure (2 of 2)the Overlapped Structure (2 of 2)

OVERLAPPED ov = { 0, 0, 0, 0, NULL };RECORD r; /* Includes “reference count” field */LONGLONG n;LARGE_INTEGER FilePos;DWORD nRd, nWrt;. . ./* Update reference count in the n’th record. */FilePos.QuadPart = n * sizeof (RECORD);ov.Offset = FilePos.LowPart;ov.OffsetHigh = FilePos.HighPart;ReadFile (hFile, &r, sizeof(RECORD), &nRd, &ov);r.RefCount++; /* Update the record. */WriteFile(hFile, &r, sizeof(RECORD), &nWrt, &ov);

Page 52: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

52JMH Associates © 2004, All rights reserved

TOPIC VITOPIC VITOPIC VITOPIC VI

File Locking

Page 53: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

53JMH Associates © 2004, All rights reserved

FILE LOCKING (1 of 5)FILE LOCKING (1 of 5)FILE LOCKING (1 of 5)FILE LOCKING (1 of 5)

Lock all or part of a file Lock can be read-only (sharable) or read-write (exclusive) Lock belongs to a process

Any attempt to access part of a file (using ReadFile or WriteFile) in violation of a lock will fail

You cannot create conflicting locks on a file Specify whether you should wait for a lock to become

available, or thread can return immediately, indicating whether it obtained the lock

Page 54: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

54JMH Associates © 2004, All rights reserved

FILE LOCKING (2 of 5)FILE LOCKING (2 of 5)FILE LOCKING (2 of 5)FILE LOCKING (2 of 5)

BOOL LockFileEx (HANDLE hFile, DWORD dwFlags,DWORD dwReserved,DWORD nNumberOfBytesToLockLow,DWORD nNumberOfBytesToLockHigh,LPOVERLAPPED lpOverlapped)

Locks a byte range in an open file for shared (multiple readers) or exclusive (one reader-writer) access

Page 55: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

55JMH Associates © 2004, All rights reserved

FILE LOCKING (3 of 5)FILE LOCKING (3 of 5)FILE LOCKING (3 of 5)FILE LOCKING (3 of 5)

Parameters hFile — Handle of an open file which must have at least

one of GENERIC_READ or GENERIC_WRITE access dwFlags — Determines the lock mode and whether to wait

for the lock to become available LOCKFILE_EXCLUSIVE_LOCK, if set, indicates a request for

an exclusive, read-write, lock; otherwise, it requests a shared (read only) lock

LOCKFILE_FAIL_IMMEDIATELY, if set, specifies that the function should return immediately with a FALSE if the lock cannot be acquired; otherwise, the call blocks until the lock becomes available

Page 56: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

56JMH Associates © 2004, All rights reserved

FILE LOCKING (4 of 5)FILE LOCKING (4 of 5)FILE LOCKING (4 of 5)FILE LOCKING (4 of 5)

dwReserved must be zero lpOverlapped — Points to an OVERLAPPED data structure

containing the start of the byte range The OVERLAPPED structure contains two data members that

must be set (the others are ignored), namely: DWORD Offset and DWORD OffsetHigh

A file lock is removed with a corresponding UnlockFileEx call, using all the same parameters except for dwFlags

Page 57: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

57JMH Associates © 2004, All rights reserved

FILE LOCKING (5 of 5)FILE LOCKING (5 of 5)FILE LOCKING (5 of 5)FILE LOCKING (5 of 5)

BOOL UnlockFileEx (HANDLE hFile,DWORD dwReserved,DWORD nNumberOfBytesToLockLow,DWORD nNumberOfBytesToLockHigh,LPOVERLAPPED lpOverlapped)

Page 58: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

58JMH Associates © 2004, All rights reserved

FILE LOCKING IN WINDOWS 9xFILE LOCKING IN WINDOWS 9xFILE LOCKING IN WINDOWS 9xFILE LOCKING IN WINDOWS 9x

Exclusive locks only

BOOL LockFile (HANDLE hFile,DWORD dwOffsetLow, DWORD dwOffsetHighDWORD nNumberOfBytesToLockLow,DWORD nNumberOfBytesToLockHigh)

BOOL UnlockFile (HANDLE hFile,DWORD dwOffsetLow, DWORD dwOffsetHighDWORD nNumberOfBytesToLockLow,DWORD nNumberOfBytesToLockHigh)

Page 59: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

59JMH Associates © 2004, All rights reserved

FILE LOCKING CONSIDERATIONSFILE LOCKING CONSIDERATIONSFILE LOCKING CONSIDERATIONSFILE LOCKING CONSIDERATIONS

The unlock must use exactly the same range as a preceding lock

Locks cannot overlap existing locked regions in a file You can lock beyond the range of a file’s length Locks are not inherited by a newly created process

Page 60: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

60JMH Associates © 2004, All rights reserved

LOCK REQUEST LOGICLOCK REQUEST LOGICLOCK REQUEST LOGICLOCK REQUEST LOGIC

Requested Lock Type

Existing Lock Shared LockExclusive Lock

None Granted Granted

Shared LockGranted Refused(one or more)

Exclusive Lock Refused Refused

Page 61: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

61JMH Associates © 2004, All rights reserved

I/O Operation

Existing Lock Read Write

None Succeeds Succeeds

Shared LockSucceeds. It is not Refused(one or more) necessary for the calling

process to own a lockon the file region.

Exclusive Lock Succeeds if the calling process owns thelock. Fails otherwise.

LOCKS AND I/O OPERATIONLOCKS AND I/O OPERATIONLOCKS AND I/O OPERATIONLOCKS AND I/O OPERATION

Page 62: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

62JMH Associates © 2004, All rights reserved

FILE LOCKS—SUMMARY (1 of 2)FILE LOCKS—SUMMARY (1 of 2)FILE LOCKS—SUMMARY (1 of 2)FILE LOCKS—SUMMARY (1 of 2)

A failed read or write may take the form of a partially complete operation if only a portion of the read or write record is locked

Read and write operations are normally in the form of ReadFile and WriteFile calls, or ReadFileEx and WriteFileEx

Diagnosing a read or write failure requires calling GetLastError

Accessing memory that is mapped to a file is another form of file I/O

Page 63: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

63JMH Associates © 2004, All rights reserved

FILE LOCKS—SUMMARY (2 of 2)FILE LOCKS—SUMMARY (2 of 2)FILE LOCKS—SUMMARY (2 of 2)FILE LOCKS—SUMMARY (2 of 2)

Lock conflicts are not detected at the time of memory reference; rather, they are detected at the time MapViewOfFile is called

The LockFile function is a limited, special case which gives exclusive access and returns immediately

Page 64: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

64JMH Associates © 2004, All rights reserved

Part VIIPart VIIPart VIIPart VII

File and Directory Management

Page 65: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

65JMH Associates © 2004, All rights reserved

FILE AND DIRECTORY MANAGEMENTFILE AND DIRECTORY MANAGEMENTFILE AND DIRECTORY MANAGEMENTFILE AND DIRECTORY MANAGEMENT

BOOL DeleteFile (LPCTSTR lpFileName)

You cannot delete an open file in Windows NT

(You can in Windows 9x)

Page 66: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

66JMH Associates © 2004, All rights reserved

FILE AND DIRECTORY MANAGEMENTFILE AND DIRECTORY MANAGEMENT—RENAMING (1 of 2)—RENAMING (1 of 2)

FILE AND DIRECTORY MANAGEMENTFILE AND DIRECTORY MANAGEMENT—RENAMING (1 of 2)—RENAMING (1 of 2)

BOOL MoveFile (LPCTSTR lpExisting,LPCTSTR lpNew)

Source and target files must be on the same drive

BOOL MoveFileEx (LPCTSTR lpExisting,LPCTSTR lpNew, DWORD dwFlags)

Source and target files can be on different drives

Note: There are no links as in UNIX Neither soft links nor hard links Shortcuts are not the same thing; they are only recognized

by the visual shell

Page 67: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

67JMH Associates © 2004, All rights reserved

FILE AND DIRECTORY MANAGEMENTFILE AND DIRECTORY MANAGEMENT—RENAMING (2 of 2)—RENAMING (2 of 2)

FILE AND DIRECTORY MANAGEMENTFILE AND DIRECTORY MANAGEMENT—RENAMING (2 of 2)—RENAMING (2 of 2)

Parameters

lpExisting — The name of the existing file or directory

lpNew — Cannot exist with MoveFile Must be on same drive

dwFlags MOVEFILE_REPLACE_EXISTING

To replace an existing file MOVEFILE_COPY_ALLOWED

Copy then delete

Page 68: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

68JMH Associates © 2004, All rights reserved

DIRECTORY MANAGEMENT (1 of 4)DIRECTORY MANAGEMENT (1 of 4)DIRECTORY MANAGEMENT (1 of 4)DIRECTORY MANAGEMENT (1 of 4)

BOOL CreateDirectory (LPCTSTR lpPath,LPSECURITY_ATTRIBUTES lpsa)

BOOL RemoveDirectory (LPCTSTR lpPath)

lpPath Points to a null-terminated string with the directory name

Page 69: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

69JMH Associates © 2004, All rights reserved

DIRECTORY MANAGEMENT (2 of 4)DIRECTORY MANAGEMENT (2 of 4)DIRECTORY MANAGEMENT (2 of 4)DIRECTORY MANAGEMENT (2 of 4)

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

Page 70: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

70JMH Associates © 2004, All rights reserved

DIRECTORY MANAGEMENT (3 of 4)DIRECTORY MANAGEMENT (3 of 4)DIRECTORY MANAGEMENT (3 of 4)DIRECTORY MANAGEMENT (3 of 4)

DWORD GetCurrentDirectory (DWORD cchCurDir,

LPTSTR lpCurDir)

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

Page 71: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

71JMH Associates © 2004, All rights reserved

DIRECTORY MANAGEMENT (4 of 4)DIRECTORY MANAGEMENT (4 of 4)DIRECTORY MANAGEMENT (4 of 4)DIRECTORY MANAGEMENT (4 of 4)

Windows uses this technique whenever the result’s length is not known

Parameters

cchCurDir Character length of the buffer for the directory name

cch - “Count in characters”

lpCurDir Points to the buffer to receive the pathname string

Page 72: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

72JMH Associates © 2004, All rights reserved

TESTING TESTING GetCurrentDirectoryGetCurrentDirectory FOR FOR CORRECT OPERATIONCORRECT OPERATION

TESTING TESTING GetCurrentDirectoryGetCurrentDirectory FOR FOR CORRECT OPERATIONCORRECT OPERATION

/* pwd: Print the working directory. Similar to the UNIX pwd command *//* This program illustrates: 1. Windows GetCurrentDirectory 2. Testing the length of a returned string */#include "EvryThng.h"

#define DIRNAME_LEN MAX_PATH + 2int main (int argc, LPCTSTR argv []){ /* Buffer to receive current directory allows CR/LF at the end of the longest possible path. */ TCHAR pwdBuffer [DIRNAME_LEN];

Page 73: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

73JMH Associates © 2004, All rights reserved

GetCurrentDirectoryGetCurrentDirectory (2 of 2) (2 of 2)GetCurrentDirectoryGetCurrentDirectory (2 of 2) (2 of 2)

DWORD LenCurDir; LenCurDir = GetCurrentDirectory (DIRNAME_LEN, pwdBuffer); if (LenCurDir == 0) ReportError (TEXT ("Failure getting pathname\n"), 1, TRUE); if (LenCurDir > DIRNAME_LEN) ReportError (TEXT ("Pathname is too long\n"), 2, FALSE);

PrintMsg (GetStdHandle (STD_OUTPUT_HANDLE), pwdBuffer); return 0;}

Page 74: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

74JMH Associates © 2004, All rights reserved

FILE ATTRIBUTES ANDFILE ATTRIBUTES ANDFILE SEARCHING (1 of 2)FILE SEARCHING (1 of 2)FILE ATTRIBUTES ANDFILE ATTRIBUTES AND

FILE SEARCHING (1 of 2)FILE SEARCHING (1 of 2)

HANDLE FindFirstFile (LPCTSTR lpSearchFile,

LPWIN32_FIND_DATA lpffd)

Return: A “search handle” INVALID_HANDLE_VALUE indicates failure

Parameters lpSearchFile — Points to directory or pathname.

Wildcards are OK (* and ?) lpffd — Points to a WIN32_FIND_DATA structure

Page 75: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

75JMH Associates © 2004, All rights reserved

FILE ATTRIBUTES ANDFILE ATTRIBUTES ANDFILE SEARCHING (2 of 2)FILE SEARCHING (2 of 2)FILE ATTRIBUTES ANDFILE ATTRIBUTES AND

FILE SEARCHING (2 of 2)FILE SEARCHING (2 of 2)

typedef struct _WIN32_FIND_DATA {DWORD dwFileAttributes; /* see CreateFile */FILETIME ftCreationTime; /* 64-bit int */FILETIME ftLastAccessTime;FILETIME ftLastWriteTime;DWORD nFileSizeHigh;DWORD nFileSizeLow;DWORD dwReserved0;DWORD dwReserved1;TCHAR cFileName [MAX_PATH]; /* file name */TCHAR cAlternateFileName [14]; /* 8.3 name */

} WIN32_FIND_DATA;

Page 76: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

76JMH Associates © 2004, All rights reserved

FILES AND DIRECTORIES (1 of 5)FILES AND DIRECTORIES (1 of 5)FILES AND DIRECTORIES (1 of 5)FILES AND DIRECTORIES (1 of 5)

BOOL FindNextFile (HANDLE hFindFile,LPWIN32_FIND_DATA lpffd)

FALSE when no more files satisfy the search pattern

BOOL FindClose (HANDLE hFindFile) Exception: This is an example of a HANDLE that is not

closed with CloseHandle.

Page 77: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

77JMH Associates © 2004, All rights reserved

FILES AND DIRECTORYS (2 of 5)FILES AND DIRECTORYS (2 of 5)FILES AND DIRECTORYS (2 of 5)FILES AND DIRECTORYS (2 of 5)

File attributes can be obtained individually Usually from the HANDLE rather than file name

DWORD GetFileSize (HANDLE hFile,

LPDWORD lpdwFileSizeHigh)

Return: The low-order component of the file size 0xFFFFFFFF indicates a possible error; check GetLastError

Page 78: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

78JMH Associates © 2004, All rights reserved

FILES AND DIRECTORYS (3 of 5)FILES AND DIRECTORYS (3 of 5)FILES AND DIRECTORYS (3 of 5)FILES AND DIRECTORYS (3 of 5)

DWORD GetFileInformationByHandle (HANDLE hFile)

Use GetCompressedFileSize to test for an empty file if you have the file name but do not have an open handle

Page 79: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

79JMH Associates © 2004, All rights reserved

FILES AND DIRECTORYS (4 of 5)FILES AND DIRECTORYS (4 of 5)FILES AND DIRECTORYS (4 of 5)FILES AND DIRECTORYS (4 of 5)BOOL GetFileTime (HANDLE hFile,

LPFILETIME lpftCreation,LPFILETIME lpftLastAccess,LPFILETIME lpftLastWrite)

BOOL FileTimeToSystemTime(CONST FILETIME * lpFileTime,LPSYSTEMTIME lpSystemTime)

LPSYSTEMTIME has WORD members for the time components:

wYear, wMonth, …, wMilliseconds

FILETIME (64 bits) is elapsed 100 ns units since Jan 1, 1601

More than 60,000 years can be represented

Page 80: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

80JMH Associates © 2004, All rights reserved

FILES AND DIRECTORYS (5 of 5)FILES AND DIRECTORYS (5 of 5)FILES AND DIRECTORYS (5 of 5)FILES AND DIRECTORYS (5 of 5)

DWORD GetFileAttributes (LPCTSTR lpFileName)

Return: The file attributes or 0xFFFFFFFF in case of failure The attributes can be tested for the following values:

FILE_ATTRIBUTE_DIRECTORY FILE_ATTRIBUTE_NORMAL FILE_ATTRIBUTE_READONLY FILE_ATTRIBUTE_TEMPORARY

SetFileAttributes Allows you to change attributes in a named file

Page 81: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

81JMH Associates © 2004, All rights reserved

TEMPORARY FILE NAMES (1 of 2)TEMPORARY FILE NAMES (1 of 2)TEMPORARY FILE NAMES (1 of 2)TEMPORARY FILE NAMES (1 of 2)

UINT GetTempFileName (LPCTSTR lpPath,LPCTSTR lpPrefix, UINT uUnique,LPTSTR lpTempFile)

Return: A unique numeric value used to create the file name

uUnique if uUnique is non-zero On failure, the return value is zero.

Page 82: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

82JMH Associates © 2004, All rights reserved

TEMPORARY FILE NAMES (2 of 2)TEMPORARY FILE NAMES (2 of 2)TEMPORARY FILE NAMES (2 of 2)TEMPORARY FILE NAMES (2 of 2)

lpPath Directory where you want the temporary file

lpPrefix Prefix of the temporary name

uUnique Normally zero to generate a unique four-digit suffix

lpTempFile Points to buffer for the temporary file name

Page 83: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

83JMH Associates © 2004, All rights reserved

LAB 3–B (Option 1)LAB 3–B (Option 1)LAB 3–B (Option 1)LAB 3–B (Option 1)

Option 1

Create a program, pwdA, based on the existing pwd so that you do not need to know the maximum pathname length ahead of time

Determine the number of characters in the current directory, allocate the required memory, and then call GetCurrentDirectory () a second time

Note: This option is easy; you should select another one as well.

Page 84: 1 JMH Associates © 2004, All rights reserved Chapters 2-3 Input/Output With File and Directory Processing

84JMH Associates © 2004, All rights reserved

LAB 3–B (Options 2 and 3)LAB 3–B (Options 2 and 3)LAB 3–B (Options 2 and 3)LAB 3–B (Options 2 and 3)

Option 2 (file attributes and directory scanning)

Create a program, ls, to list the attributes (size and times) of each file and directory, starting at a specified path

Option 3 (direct file access)

Write a program, tail, that will display the last ten lines of a text file