Klasa CFileCFile Class
Klasa bazowa klas plików klas Microsoft Foundation.The base class for Microsoft Foundation Class file classes.
SkładniaSyntax
class CFile : public CObject
Elementy członkowskieMembers
Konstruktory publicznePublic Constructors
NazwaName | OpisDescription |
---|---|
CFile:: CFileCFile::CFile | Konstruuje CFile obiekt ze ścieżki lub dojścia do pliku.Constructs a CFile object from a path or file handle. |
Metody publicznePublic Methods
NazwaName | OpisDescription |
---|---|
CFile:: AbortCFile::Abort | Zamyka plik, ignorując wszystkie ostrzeżenia i błędy.Closes a file ignoring all warnings and errors. |
CFile:: CloseCFile::Close | Zamyka plik i usuwa obiekt.Closes a file and deletes the object. |
CFile::D uplikujCFile::Duplicate | Tworzy zduplikowany obiekt na podstawie tego pliku.Constructs a duplicate object based on this file. |
CFile:: FlushCFile::Flush | Opróżnia wszystkie dane, które mają być zapisywane.Flushes any data yet to be written. |
CFile:: GetFileNameCFile::GetFileName | Pobiera nazwę pliku wybranego.Retrieves the filename of the selected file. |
CFile:: GetFilePathCFile::GetFilePath | Pobiera pełną ścieżkę pliku wybranego pliku.Retrieves the full file path of the selected file. |
CFile:: GetFileTitleCFile::GetFileTitle | Pobiera tytuł wybranego pliku.Retrieves the title of the selected file. |
CFile:: GetLengthCFile::GetLength | Pobiera długość pliku.Retrieves the length of the file. |
CFile:: GetPositionCFile::GetPosition | Pobiera bieżący wskaźnik pliku.Retrieves the current file pointer. |
CFile:: GetStatusCFile::GetStatus | Pobiera stan otwartego pliku lub w wersji statycznej, Pobiera stan określonego pliku (statyczna, funkcja wirtualna).Retrieves the status of the open file, or in the static version, retrieves the status of the specified file (static, virtual function). |
CFile:: LockRangeCFile::LockRange | Blokuje zakres bajtów w pliku.Locks a range of bytes in a file. |
CFile:: OpenCFile::Open | Bezpiecznie otwiera plik z opcją testowania błędów.Safely opens a file with an error-testing option. |
CFile:: ReadCFile::Read | Odczytuje (niebuforowane) dane z pliku w bieżącym położeniu.Reads (unbuffered) data from a file at the current file position. |
CFile:: RemoveCFile::Remove | Usuwa określony plik (funkcja statyczna).Deletes the specified file (static function). |
CFile:: RenameCFile::Rename | Zmienia nazwę określonego pliku (funkcja statyczna).Renames the specified file (static function). |
CFile:: SeekCFile::Seek | Określa położenie bieżącego wskaźnika pliku.Positions the current file pointer. |
CFile:: SeekToBeginCFile::SeekToBegin | Ustawia bieżący wskaźnik pliku na początku pliku.Positions the current file pointer at the beginning of the file. |
CFile:: SeekToEndCFile::SeekToEnd | Ustawia bieżący wskaźnik pliku na końcu pliku.Positions the current file pointer at the end of the file. |
CFile:: SetFilePathCFile::SetFilePath | Ustawia pełną ścieżkę pliku dla wybranego pliku.Sets the full file path of the selected file. |
CFile:: SetLengthCFile::SetLength | Zmienia długość pliku.Changes the length of the file. |
CFile:: SetStatusCFile::SetStatus | Ustawia stan określonego pliku (statyczna, wirtualna funkcja).Sets the status of the specified file (static, virtual function). |
CFile:: UnlockRangeCFile::UnlockRange | Odblokowuje zakres bajtów w pliku.Unlocks a range of bytes in a file. |
CFile:: WriteCFile::Write | Zapisuje (niebuforowane) dane w pliku do bieżącego położenia pliku.Writes (unbuffered) data in a file to the current file position. |
Operatory publicznePublic Operators
NazwaName | OpisDescription |
---|---|
CFile:: uchwyt operatoraCFile::operator HANDLE | Dojście do CFile obiektu.A handle to a CFile object. |
Publiczne elementy członkowskie danychPublic Data Members
NazwaName | OpisDescription |
---|---|
CFile:: hFileNullCFile::hFileNull | Określa, czy CFile obiekt ma prawidłowe dojście.Determines if the CFile object has a valid handle. |
CFile:: m_hFileCFile::m_hFile | Zwykle zawiera dojście do pliku systemu operacyjnego.Usually contains the operating-system file handle. |
Chronione elementy członkowskie danychProtected Data Members
NazwaName | OpisDescription |
---|---|
CFile:: m_pTMCFile::m_pTM | Wskaźnik do CAtlTransactionManager obiektu.Pointer to CAtlTransactionManager object. |
UwagiRemarks
Zapewnia bezpośrednią pamięć podbuforowaną, dane wejściowe/wyjściowe na dyskach binarnych i pośrednio obsługuje pliki tekstowe i pliki pamięci za poorednictwem klas pochodnych.It directly provides unbuffered, binary disk input/output services, and it indirectly supports text files and memory files through its derived classes. CFile
działa w połączeniu z CArchive
klasą do obsługi serializacji obiektów klasy Microsoft Foundation.CFile
works in conjunction with the CArchive
class to support serialization of Microsoft Foundation Class objects.
Hierarchiczna relacja między tą klasą i jej klasami pochodnymi umożliwia programowi wykonywanie operacji na wszystkich obiektach plików za pomocą interfejsu polimorficznego CFile
.The hierarchical relationship between this class and its derived classes allows your program to operate on all file objects through the polymorphic CFile
interface. Plik pamięci, na przykład, zachowuje się jak plik dysku.A memory file, for example, behaves like a disk file.
Użyj CFile
i jej klas pochodnych dla operacji we/wy dysku ogólnego przeznaczenia.Use CFile
and its derived classes for general-purpose disk I/O. Użyj ofstream
lub innych klas firmy Microsoft iostream
dla sformatowanego tekstu wysyłanego do pliku dyskowego.Use ofstream
or other Microsoft iostream
classes for formatted text sent to a disk file.
Zwykle plik dyskowy jest otwierany automatycznie podczas CFile
budowania i zamykany podczas niszczenia.Normally, a disk file is opened automatically on CFile
construction and closed on destruction. Statyczne funkcje Członkowskie umożliwiają przejrzeć stanu pliku bez otwierania pliku.Static member functions permit you to interrogate a file's status without opening the file.
Aby uzyskać więcej informacji na temat korzystania z programu CFile
, zapoznaj się z artykułami pliki w bibliotece MFC i Obsługa plików w dokumentacji dotyczącej biblioteki wykonawczej.For more information on using CFile
, see the articles Files in MFC and File Handling in the Run-Time Library Reference.
Hierarchia dziedziczeniaInheritance Hierarchy
CFile
WymaganiaRequirements
Nagłówek: AFX. hHeader: afx.h
CFile:: AbortCFile::Abort
Zamyka plik skojarzony z tym obiektem i sprawia, że plik jest niedostępny do odczytu lub zapisu.Closes the file associated with this object and makes the file unavailable for reading or writing.
virtual void Abort();
UwagiRemarks
Jeśli plik nie został zamknięty przed zniszczeniem obiektu, destruktor zamknie go.If you haven't closed the file before destroying the object, the destructor closes it for you.
Obsługa wyjątków różni się CFile::Abort
od CFile::Close
na dwa sposoby.When handling exceptions, CFile::Abort
differs from CFile::Close
in two important ways. Najpierw Abort
Funkcja nie zgłosi wyjątku w przypadku błędów, ponieważ błędy są ignorowane przez Abort
.First, the Abort
function won't throw an exception on failures, because failures are ignored by Abort
. Abort
Jeśli plik nie został otwarty lub został wcześniej zamknięty, nie zostanie zaakceptowany.Second, Abort
won't ASSERT if the file hasn't been opened, or was closed previously.
Jeśli użyto new
do przydzielenia CFile
obiektu na stercie, należy go usunąć po zamknięciu pliku.If you used new
to allocate the CFile
object on the heap, then you must delete it after closing the file. Abort
ustawia m_hFile
jako CFile::hFileNull
.Abort
sets m_hFile
to CFile::hFileNull
.
PrzykładExample
CStdioFile fileTest;
TCHAR* pszFileName = _T("Abort_File.dat");
// do stuff that may cause exceptions
CFileException ex;
if (!fileTest.Open(pszFileName, CFile::modeWrite, &ex))
{
ex.ReportError();
fileTest.Abort(); // close file safely and quietly
}
CFile:: CFileCFile::CFile
Konstruuje i inicjuje CFile
obiekt.Constructs and initializes a CFile
object.
CFile();
CFile(CAtlTransactionManager* pTM);
CFile(HANDLE hFile);
CFile(
LPCTSTR lpszFileName,
UINT nOpenFlags);
CFile(
LPCTSTR lpszFileName,
UINT nOpenFlags,
CAtlTransactionManager* pTM);
ParametryParameters
hFilehFile
Dojście pliku do dołączenia do CFile
obiektu.Handle of a file to attach to the CFile
object.
lpszFileNamelpszFileName
Względna lub pełna ścieżka pliku do dołączenia do CFile
obiektu.Relative or full path of a file to attach to the CFile
object.
nOpenFlagsnOpenFlags
Kombinacja bitowa (lub) opcji dostępu do pliku dla określonego pliku.Bitwise combination (OR) of file access options for the specified file. Zobacz sekcję Uwagi, aby poznać możliwe opcje.See the Remarks section for possible options.
pTMpTM
Wskaźnik do obiektu CAtlTransactionManagerPointer to CAtlTransactionManager object
UwagiRemarks
W poniższych pięciu tabelach przedstawiono możliwe opcje parametru nOpenFlags .The following five tables list the possible options for the nOpenFlags parameter.
Wybierz tylko jedną z następujących opcji trybu dostępu do pliku.Choose only one of the following file access mode options. Domyślny tryb dostępu do pliku to CFile::modeRead
, który jest tylko do odczytu.The default file access mode is CFile::modeRead
, which is read only.
WartośćValue | OpisDescription |
---|---|
CFile::modeRead |
Żąda dostępu tylko do odczytu.Requests read access only. |
CFile::modeWrite |
Żądania dostępu tylko do zapisu.Requests write access only. |
CFile::modeReadWrite |
Żąda dostępu do odczytu i zapisu.Requests read and write access. |
Wybierz jedną z następujących opcji trybu znakowego.Choose one of the following character mode options.
WartośćValue | OpisDescription |
---|---|
CFile::typeBinary |
Ustawia tryb binarny (używany tylko w klasach pochodnych).Sets binary mode (used in derived classes only). |
CFile::typeText |
Ustawia tryb tekstowy ze specjalnym przetwarzaniem par wysuwu wiersza powrotu karetki (używane tylko w klasach pochodnych).Sets text mode with special processing for carriage return-line feed pairs (used in derived classes only). |
CFile::typeUnicode |
Ustawia tryb Unicode (używany tylko w klasach pochodnych).Sets Unicode mode (used in derived classes only). Tekst jest zapisywana w pliku w formacie Unicode, gdy aplikacja jest wbudowana w konfigurację Unicode.Text is written to the file in Unicode format when the application is built in a Unicode configuration. W pliku nie zapisano BOM.No BOM is written to the file. |
Wybierz tylko jedną z następujących opcji trybu udostępniania plików.Choose only one of the following file share mode options. Domyślny tryb udziału plików to CFile::shareExclusive
, który jest na wyłączność.The default file share mode is CFile::shareExclusive
, which is exclusive.
WartośćValue | OpisDescription |
---|---|
CFile::shareDenyNone |
Brak ograniczeń udostępniania.No sharing restrictions. |
CFile::shareDenyRead |
Odmowa dostępu do odczytu dla wszystkich innych użytkowników.Denies read access to all others. |
CFile::shareDenyWrite |
Odmawia dostępu do zapisu innym osobom.Denies write access to all others. |
CFile::shareExclusive |
Odmawia dostępu do odczytu i zapisu dla wszystkich innych użytkowników.Denies read and write access to all others. |
Wybierz pierwszy lub oba te opcje trybu tworzenia pliku.Choose the first, or both, of the following file creation mode options. Domyślny tryb tworzenia to CFile::modeNoTruncate
, który jest otwarty istniejące.The default creation mode is CFile::modeNoTruncate
, which is open existing.
WartośćValue | OpisDescription |
---|---|
CFile::modeCreate |
Tworzy nowy plik, jeśli plik nie istnieje.Creates a new file if no file exists. Jeśli plik już istnieje, zostanie nadpisany i początkowo ustawiony na zerową długość.If the file already exists, it's overwritten and initially set to zero length. |
CFile::modeNoTruncate |
Tworzy nowy plik, jeśli plik nie istnieje; w przeciwnym razie, jeśli plik już istnieje, jest dołączony do CFile obiektu.Creates a new file if no file exists; otherwise, if the file already exists, it's attached to the CFile object. |
Wybierz poniższe opcje buforowania plików zgodnie z opisem.Choose the following file caching options as described. Domyślnie system używa schematu buforowania ogólnego przeznaczenia, który nie jest dostępny jako opcja.By default, the system uses a general-purpose caching scheme that isn't available as an option.
WartośćValue | OpisDescription |
---|---|
CFile::osNoBuffer |
System nie używa pośredniej pamięci podręcznej dla tego pliku.The system doesn't use an intermediate cache for the file. Ta opcja powoduje anulowanie następujących 2 opcji.This option cancels the following 2 options. |
CFile::osRandomAccess |
Pamięć podręczna plików jest zoptymalizowana pod kątem dostępu losowego.The file cache is optimized for random access. Nie należy używać obu tych opcji i opcji skanowania sekwencyjnego.Don't use both this option and the sequential scan option. |
CFile::osSequentialScan |
Pamięć podręczna plików jest zoptymalizowana pod kątem dostępu sekwencyjnego.The file cache is optimized for sequential access. Nie używaj tej opcji i opcji dostępu swobodnego.Don't use both this option and the random access option. |
CFile::osWriteThrough |
Operacje zapisu są wykonywane bez opóźnień.Write operations are done without delay. |
Aby zapobiec dziedziczeniu dojścia do pliku, wybierz następującą opcję zabezpieczeń.Choose the following security option to prevent the file handle from being inherited. Domyślnie wszystkie nowe procesy podrzędne mogą korzystać z dojścia do pliku.By default, any new child processes can use the file handle.
WartośćValue | OpisDescription |
---|---|
CFile::modeNoInherit |
Uniemożliwia procesom podrzędnym korzystanie z dojścia do pliku.Prevents any child processes from using the file handle. |
Konstruktor domyślny inicjuje członków, ale nie dołącza pliku do CFile
obiektu.The default constructor initializes members but doesn't attach a file to the CFile
object. Po użyciu tego konstruktora Użyj metody CFile:: Open , aby otworzyć plik i dołączyć go do CFile
obiektu.After using this constructor, use the CFile::Open method to open a file and attach it to the CFile
object.
Konstruktor z jednym parametrem inicjuje członków i dołącza istniejący plik do CFile
obiektu.The constructor with one parameter initializes members and attaches an existing file to the CFile
object.
Konstruktor z dwoma parametrami inicjuje członków i próbuje otworzyć określony plik.The constructor with two parameters initializes members and tries to open the specified file. Jeśli ten Konstruktor pomyślnie otworzy określony plik, plik zostanie dołączony do CFile
obiektu; w przeciwnym razie ten konstruktor zgłosi wskaźnik do CInvalidArgException
obiektu.If this constructor successfully opens the specified file, the file is attached to the CFile
object; otherwise, this constructor throws a pointer to a CInvalidArgException
object. Aby uzyskać więcej informacji na temat obsługi wyjątków, zobacz wyjątki.For more information about how to handle exceptions, see Exceptions.
Jeśli CFile
obiekt pomyślnie otworzy określony plik, zamknie ten plik automatycznie, gdy CFile
obiekt zostanie zniszczony; w przeciwnym razie musisz jawnie zamknąć ten plik, gdy nie jest już dołączony do CFile
obiektu.If a CFile
object successfully opens a specified file, it will close this file automatically when the CFile
object is destroyed; otherwise, you must explicitly close the file after it's no longer attached to the CFile
object.
PrzykładExample
Poniższy kod pokazuje, jak używać CFile
.The following code shows how to use a CFile
.
HANDLE hFile = CreateFile(_T("CFile_File.dat"),
GENERIC_WRITE, FILE_SHARE_READ,
NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
AfxMessageBox(_T("Couldn't create the file!"));
}
else
{
// Attach a CFile object to the handle we have.
CFile myFile(hFile);
static const TCHAR sz[] = _T("I love CFile!");
// write string
myFile.Write(sz, sizeof(sz));
// We need to call Close() explicitly. Note that there's no need to
// call CloseHandle() on the handle returned by the API because
// Close() automatically calls CloseHandle() for us.
myFile.Close();
CFile:: CloseCFile::Close
Zamyka plik skojarzony z tym obiektem i sprawia, że plik jest niedostępny do odczytu lub zapisu.Closes the file associated with this object and makes the file unavailable for reading or writing.
virtual void Close();
UwagiRemarks
Jeśli plik nie został zamknięty przed zniszczeniem obiektu, destruktor zamknie go.If you haven't closed the file before destroying the object, the destructor closes it for you.
Jeśli użyto new
do przydzielenia CFile
obiektu na stercie, należy go usunąć po zamknięciu pliku.If you used new
to allocate the CFile
object on the heap, then you must delete it after closing the file. Close
ustawia m_hFile
jako CFile::hFileNull
.Close
sets m_hFile
to CFile::hFileNull
.
PrzykładExample
Zobacz przykład dla CFile:: CFile.See the example for CFile::CFile.
CFile::D uplikujCFile::Duplicate
Tworzy zduplikowany CFile
obiekt dla danego pliku.Constructs a duplicate CFile
object for a given file.
virtual CFile* Duplicate() const;
Wartość zwracanaReturn Value
Wskaźnik do zduplikowanego CFile
obiektu.A pointer to a duplicate CFile
object.
UwagiRemarks
Ta funkcja jest równoważna z funkcją C Run-Time _dup
.This function is equivalent to the C run-time function _dup
.
CFile:: FlushCFile::Flush
Wymusza, aby wszystkie pozostałe dane w buforze plików były zapisywane do pliku.Forces any data remaining in the file buffer to be written to the file.
virtual void Flush();
UwagiRemarks
Użycie Flush
nie gwarantuje opróżniania CArchive
buforów.The use of Flush
doesn't guarantee flushing of CArchive
buffers. Jeśli używasz archiwum, najpierw Wywołaj CArchive:: Flush .If you're using an archive, call CArchive::Flush first.
PrzykładExample
Zobacz przykład dla CFile:: SetFilePath.See the example for CFile::SetFilePath.
CFile:: GetFileNameCFile::GetFileName
Wywołaj tę funkcję elementu członkowskiego, aby pobrać nazwę określonego pliku.Call this member function to retrieve the name of a specified file.
virtual CString GetFileName() const;
Wartość zwracanaReturn Value
Nazwa pliku.The name of the file.
UwagiRemarks
Na przykład po wywołaniu GetFileName
w celu wygenerowania komunikatu o pliku zostanie c:\windows\write\myfile.wri
zwrócona nazwa pliku, myfile.wri
.For example, when you call GetFileName
to generate a message to the user about the file c:\windows\write\myfile.wri
, the filename, myfile.wri
, is returned.
Aby zwrócić całą ścieżkę pliku, w tym nazwę, wywołaj metodę GetFilePath.To return the entire path of the file, including the name, call GetFilePath. Aby zwrócić tytuł pliku ( myfile
), wywołaj GetFileTitle.To return the title of the file ( myfile
), call GetFileTitle.
PrzykładExample
Ten fragment kodu otwiera SYSTEM.INI plik w katalogu systemu WINDOWS.This code fragment opens the SYSTEM.INI file in your WINDOWS directory. W przypadku znalezienia przykładu zostanie wyświetlona nazwa i ścieżka oraz tytuł, jak pokazano w obszarze Wyjście:If found, the example will print out the name and path and title, as shown under Output:
try
{
// try to open the file
CFile sysFile(_T("C:\\WINDOWS\\SYSTEM.INI"), CFile::modeRead);
// print out path name and title information
_tprintf_s(_T("Path is : \"%s\"\n"),
(LPCTSTR) sysFile.GetFilePath());
_tprintf_s(_T("Name is : \"%s\"\n"),
(LPCTSTR) sysFile.GetFileName());
_tprintf_s(_T("Title is: \"%s\"\n"),
(LPCTSTR) sysFile.GetFileTitle());
// close the file handle
sysFile.Close();
}
catch (CFileException* pEx)
{
// if an error occurs, just make a message box
pEx->ReportError();
pEx->Delete();
}
CFile:: GetFilePathCFile::GetFilePath
Wywołaj tę funkcję elementu członkowskiego, aby pobrać pełną ścieżkę do określonego pliku.Call this member function to retrieve the full path of a specified file.
virtual CString GetFilePath() const;
Wartość zwracanaReturn Value
Pełna ścieżka określonego pliku.The full path of the specified file.
UwagiRemarks
Na przykład po wywołaniu GetFilePath
w celu wygenerowania komunikatu dotyczącego pliku c:\windows\write\myfile.wri
c:\windows\write\myfile.wri
zostanie zwrócona ścieżka do pliku.For example, when you call GetFilePath
to generate a message to the user about the file c:\windows\write\myfile.wri
, the file path, c:\windows\write\myfile.wri
, is returned.
Aby zwrócić tylko nazwę pliku ( myfile.wri
), wywołaj GetFileName.To return just the name of the file (myfile.wri
), call GetFileName. Aby zwrócić tytuł pliku ( myfile
), wywołaj GetFileTitle.To return the title of the file (myfile
), call GetFileTitle.
PrzykładExample
Zobacz przykład dla elementu GetFileName.See the example for GetFileName.
CFile:: GetFileTitleCFile::GetFileTitle
Wywołaj tę funkcję elementu członkowskiego, aby pobrać tytuł pliku (nazwa wyświetlana) dla tego pliku.Call this member function to retrieve the file title (the display name) for the file.
virtual CString GetFileTitle() const;
Wartość zwracanaReturn Value
Tytuł pliku źródłowego.The title of the underlying file.
UwagiRemarks
Ta metoda wywołuje GetFileTitle , aby pobrać tytuł pliku.This method calls GetFileTitle to retrieve the title of the file. Jeśli to się powiedzie, metoda zwraca ciąg używany przez system do wyświetlania nazwy pliku użytkownikowi.If successful, the method returns the string that the system would use to display the file name to the user. W przeciwnym razie metoda wywołuje PathFindFileName , aby pobrać nazwę pliku (łącznie z rozszerzeniem pliku) pliku źródłowego.Otherwise, the method calls PathFindFileName to retrieve the file name (including the file extension) of the underlying file. Oznacza to, że rozszerzenie pliku nie jest zawsze uwzględniane w ciągu tytułu zwróconego pliku.That means the file extension isn't always included in the returned file title string. Aby uzyskać więcej informacji, zobacz GetFileTitle i PathFindFileName w Windows SDK.For more information, see GetFileTitle and PathFindFileName in the Windows SDK.
Aby zwrócić całą ścieżkę pliku, w tym nazwę, wywołaj metodę GetFilePath.To return the entire path of the file, including the name, call GetFilePath. Aby zwrócić tylko nazwę pliku, wywołaj GetFileName.To return just the name of the file, call GetFileName.
PrzykładExample
Zobacz przykład dla elementu GetFileName.See the example for GetFileName.
CFile:: GetLengthCFile::GetLength
Uzyskuje bieżącą długość logiczną pliku w bajtach.Obtains the current logical length of the file in bytes.
virtual ULONGLONG GetLength() const;
Wartość zwracanaReturn Value
Długość pliku.The length of the file.
PrzykładExample
CFile* pFile = NULL;
// Constructing a CFile object with this override may throw
// a CFile exception, and won't throw any other exceptions.
// Calling CString::Format() may throw a CMemoryException,
// so we have a catch block for such exceptions, too. Any
// other exception types this function throws will be
// routed to the calling function.
try
{
pFile = new CFile(_T("C:\\WINDOWS\\SYSTEM.INI"),
CFile::modeRead | CFile::shareDenyNone);
ULONGLONG dwLength = pFile->GetLength();
CString str;
str.Format(_T("Your SYSTEM.INI file is %I64u bytes long."), dwLength);
AfxMessageBox(str);
}
catch (CFileException* pEx)
{
// Simply show an error message to the user.
pEx->ReportError();
pEx->Delete();
}
catch(CMemoryException* pEx)
{
pEx->ReportError();
pEx->Delete();
// We can't recover from this memory exception, so we'll
// just terminate the app without any cleanup. Normally,
// an application should do everything it possibly can to
// clean up properly and _not_ call AfxAbort().
AfxAbort();
}
// If an exception occurs in the CFile constructor,
// the language will free the memory allocated by new
// and will not complete the assignment to pFile.
// Thus, our clean-up code needs to test for NULL.
if (pFile != NULL)
{
pFile->Close();
delete pFile;
}
CFile:: GetPositionCFile::GetPosition
Uzyskuje bieżącą wartość wskaźnika pliku, która może być używana w późniejszych wywołaniach do Seek
.Obtains the current value of the file pointer, which can be used in later calls to Seek
.
virtual ULONGLONG GetPosition() const;
Wartość zwracanaReturn Value
Wskaźnik pliku.The file pointer.
PrzykładExample
CFile cfile;
cfile.Open(_T("Seek_File.dat"), CFile::modeCreate |
CFile::modeReadWrite);
LONGLONG lOffset = 1000;
ULONGLONG lActual;
lActual = cfile.Seek(lOffset, CFile::begin);
ASSERT(cfile.GetPosition() == lActual);
CFile:: GetStatusCFile::GetStatus
Ta metoda pobiera informacje o stanie powiązane z danym CFile
wystąpieniem obiektu lub z daną ścieżką do pliku.This method retrieves status information related to a given CFile
object instance or a given file path.
BOOL GetStatus(CFileStatus& rStatus) const;
static BOOL PASCAL GetStatus(
LPCTSTR lpszFileName,
CFileStatus& rStatus,
CAtlTransactionManager* pTM = NULL);
ParametryParameters
rStatusrStatus
Odwołanie do struktury dostarczonej przez użytkownika CFileStatus
, która będzie otrzymywać informacje o stanie.A reference to a user-supplied CFileStatus
structure that will receive the status information. CFileStatus
Struktura zawiera następujące pola:The CFileStatus
structure has the following fields:
CTime m_ctime
Data i godzina utworzenia pliku.CTime m_ctime
The date and time the file was created.CTime m_mtime
Data i godzina ostatniej modyfikacji pliku.CTime m_mtime
The date and time the file was last modified.CTime m_atime
Data i godzina ostatniego dostępu do pliku.CTime m_atime
The date and time the file was last accessed for reading.ULONGLONG m_size
Rozmiar logiczny pliku w bajtach, który został zgłoszony przez polecenie DIR.ULONGLONG m_size
The logical size of the file in bytes, as reported by the DIR command.BYTE m_attribute
Bajt atrybutu pliku.BYTE m_attribute
The attribute byte of the file.char m_szFullName[_MAX_PATH]
Bezwzględna nazwa pliku w zestawie znaków systemu Windows.char m_szFullName[_MAX_PATH]
The absolute filename in the Windows character set.
lpszFileNamelpszFileName
Ciąg w zestawie znaków systemu Windows, który jest ścieżką do żądanego pliku.A string in the Windows character set that is the path to the desired file. Ścieżka może być względna lub bezwzględna lub może zawierać nazwę ścieżki sieciowej.The path can be relative or absolute, or it can contain a network path name.
pTMpTM
Wskaźnik do obiektu CAtlTransactionManagerPointer to CAtlTransactionManager object
Wartość zwracanaReturn Value
Ma wartość TRUE, jeśli informacje o stanie określonego pliku zostaną pomyślnie pobrane. w przeciwnym razie FALSE.TRUE if the status information for the specified file is successfully obtained; otherwise, FALSE.
UwagiRemarks
Niestatyczna wersja programu GetStatus
Pobiera informacje o stanie otwartego pliku skojarzone z danym CFile
obiektem.The non-static version of GetStatus
retrieves status information of the open file associated with the given CFile
object. Wersja statyczna programu GetStatus
uzyskuje stan pliku z danej ścieżki pliku bez faktycznego otwierania pliku.The static version of GetStatus
obtains the file status from a given file path without actually opening the file. Ta wersja jest przydatna do testowania praw dostępu do pliku.This version is useful for testing the existence and access rights of a file.
m_attribute
Element członkowski CFileStatus
struktury odwołuje się do zestawu atrybutów pliku.The m_attribute
member of the CFileStatus
structure refers to the file attribute set. CFile
Klasa zawiera typ wyliczeniowy atrybutu , więc atrybuty pliku można określić symbolicznie:The CFile
class provides the Attribute enumeration type so file attributes can be specified symbolically:
enum Attribute {
normal = 0x00,
readOnly = 0x01,
hidden = 0x02,
system = 0x04,
volume = 0x08,
directory = 0x10,
archive = 0x20
};
PrzykładExample
CFile cfile;
cfile.Open(_T("SetLength_File.dat"), CFile::modeCreate |
CFile::modeReadWrite);
ULONGLONG dwNewLength = 10000;
cfile.SetLength(dwNewLength);
CFileStatus status;
if(cfile.GetStatus(status)) // virtual member function
{
TRACE(_T("File size = %u\n"), status.m_size);
}
TCHAR* pszFileName = _T("SetLength_File.dat");
if(CFile::GetStatus(pszFileName, status)) // static function
{
TRACE(_T("Full file name = %s\n"), status.m_szFullName);
}
CFile:: hFileNullCFile::hFileNull
Określa obecność prawidłowego dojścia do pliku dla CFile
obiektu.Determines the presence of a valid file handle for the CFile
object.
static AFX_DATA const HANDLE hFileNull;
UwagiRemarks
Ta stała służy do określenia, czy CFile
obiekt ma prawidłowe dojście do pliku.This constant is used to determine if the CFile
object has a valid file handle.
Poniższy przykład ilustruje tę operację:The following example demonstrates this operation:
if (myFile.m_hFile != CFile::hFileNull)
;//perform operations on the file
else
;//indicate the presence of an invalid handle
CFile:: LockRangeCFile::LockRange
Blokuje zakres bajtów w otwartym pliku, zwracając wyjątek, jeśli plik jest już zablokowany.Locks a range of bytes in an open file, throwing an exception if the file is already locked.
virtual void LockRange(
ULONGLONG dwPos,
ULONGLONG dwCount);
ParametryParameters
dwPosdwPos
Przesunięcie bajtów początku zakresu bajtów do zablokowania.The byte offset of the start of the byte range to lock.
dwCountdwCount
Liczba bajtów w zakresie do zablokowania.The number of bytes in the range to lock.
UwagiRemarks
Zablokowanie bajtów w pliku uniemożliwia dostęp do tych bajtów przez inne procesy.Locking bytes in a file prevents access to those bytes by other processes. Można zablokować więcej niż jeden region pliku, ale nie są dozwolone żadne nakładające się regiony.You can lock more than one region of a file, but no overlapping regions are allowed.
Po odblokowaniu regionu przy użyciu UnlockRange
funkcji członkowskiej zakres bajtów musi dokładnie odpowiadać regionowi, który został wcześniej zablokowany.When you unlock the region using the UnlockRange
member function, the byte range must correspond exactly to the region that was previously locked. LockRange
Funkcja nie scala sąsiadujących regionów.The LockRange
function doesn't merge adjacent regions. Jeśli dwa zablokowane regiony są sąsiadujące, należy odblokować każdy region osobno.If two locked regions are adjacent, you must unlock each region separately.
Uwaga
Ta funkcja jest niedostępna dla CMemFile
klasy pochodnej.This function isn't available for the CMemFile
-derived class.
PrzykładExample
CFile cfile;
cfile.Open(_T("LockRange_File.dat"), CFile::modeCreate |
CFile::modeReadWrite);
ULONGLONG dwPos = 10;
ULONGLONG dwCount = 100;
cfile.LockRange(dwPos, dwCount);
// do something with the file
cfile.UnlockRange(dwPos, dwCount);
CFile:: m_hFileCFile::m_hFile
Zawiera dojście do pliku systemu operacyjnego dla otwartego pliku.Contains the operating-system file handle for an open file.
HANDLE m_hFile;
UwagiRemarks
m_hFile
jest publiczną zmienną typu UINT.m_hFile
is a public variable of type UINT. Zawiera ona CFile::hFileNull
niezależny od systemu operacyjnego wskaźnik pustego pliku, jeśli dojście nie zostało przypisane.It contains CFile::hFileNull
, an operating-system-independent empty file indicator, if the handle hasn't been assigned.
Użycie m_hFile
nie jest zalecane, ponieważ znaczenie elementu członkowskiego zależy od klasy pochodnej.Use of m_hFile
isn't recommended, because the member's meaning depends on the derived class. m_hFile
jest członkiem publicznej składowej dla wygody obsługi niepolimorficznego użycia klasy.m_hFile
is made a public member for convenience in supporting nonpolymorphic use of the class.
CFile:: m_pTMCFile::m_pTM
Wskaźnik do CAtlTransactionManager
obiektu.Pointer to a CAtlTransactionManager
object.
CAtlTransactionManager* m_pTM;
UwagiRemarks
CFile:: OpenCFile::Open
Przeciążone.Overloaded. Open
jest przeznaczony do użytku z CFile
konstruktorem domyślnym.Open
is designed for use with the default CFile
constructor.
virtual BOOL Open(
LPCTSTR lpszFileName,
UINT nOpenFlags,
CFileException* pError = NULL);
virtual BOOL Open(
LPCTSTR lpszFileName,
UINT nOpenFlags,
CAtlTransactionManager* pTM,
CFileException* pError = NULL);
ParametryParameters
lpszFileNamelpszFileName
Ciąg, który zawiera ścieżkę do żądanego pliku.A string that contains the path to the desired file. Ścieżka może być względna, bezwzględna lub nazwą sieciową (UNC).The path can be relative, absolute, or a network name (UNC).
nOpenFlagsnOpenFlags
Element UINT, który definiuje tryb udostępniania i dostępu do pliku.A UINT that defines the file's sharing and access mode. Określa akcję do wykonania podczas otwierania pliku.It specifies the action to take when opening the file. Opcje można łączyć za pomocą operatora bitowego lub ( | ).You can combine options by using the bitwise-OR ( | ) operator. Wymagane są jedno uprawnienie dostępu i jedna opcja udostępniania; modeCreate
tryby i modeNoInherit
są opcjonalne.One access permission and one share option are required; the modeCreate
and modeNoInherit
modes are optional. Zapoznaj się z listą opcji trybu w konstruktorze CFile .See the CFile constructor for a list of mode options.
pErrorpError
Wskaźnik do istniejącego obiektu wyjątku pliku, który otrzyma stan operacji zakończonej niepowodzeniem.A pointer to an existing file-exception object that will receive the status of a failed operation.
pTMpTM
Wskaźnik do obiektu CAtlTransactionManagerPointer to CAtlTransactionManager object
Wartość zwracanaReturn Value
Niezerowe, jeśli otwarcie zakończyło się pomyślnie; w przeciwnym razie 0.Nonzero if the open was successful; otherwise 0. Parametr pError ma znaczenie tylko wtedy, gdy zwracana jest wartość 0.The pError parameter is meaningful only if 0 is returned.
UwagiRemarks
Te dwie Open
funkcje są "bezpiecznymi" metodami otwierania plików, w których wystąpił błąd normalny, oczekiwany warunek.The two Open
functions are "safe" methods for opening a file, where a failure is a normal, expected condition.
Chociaż CFile
Konstruktor zgłasza wyjątek w warunku błędu, Open
zwraca wartość false dla warunków błędu.While the CFile
constructor throws an exception in an error condition, Open
returns FALSE for error conditions. Open
może jednak nadal inicjować obiekt CFileException w celu opisywania błędu.Open
can still initialize a CFileException object to describe the error, however. Jeśli nie podasz parametru pError lub Jeśli przekażesz wartość null dla pError, Open
zwraca wartość false i nie generuje elementu CFileException
.If you don't supply the pError parameter, or if you pass NULL for pError, Open
returns FALSE and doesn't throw a CFileException
. Jeśli przekażesz wskaźnik do istniejącej CFileException
i Open
napotkasz błąd, funkcja wypełni ją informacjami opisującymi ten błąd.If you pass a pointer to an existing CFileException
, and Open
encounters an error, the function fills it with information describing that error. Open
nie zgłasza wyjątku w obu przypadkach.Open
doesn't throw an exception in either case.
W poniższej tabeli opisano możliwe wyniki działania programu Open
.The following table describes the possible results of Open
.
pError |
Wystąpił błądError encountered | Wartość zwracanaReturn value | Zawartość CFileExceptionCFileException content |
---|---|---|---|
NULLNULL | NieNo | TRUETRUE | n/dn/a |
PTR na CFileException ptr to CFileException |
NieNo | TRUETRUE | bez zmianunchanged |
NULLNULL | TakYes | FALSEFALSE | n/dn/a |
PTR na CFileException ptr to CFileException |
TakYes | FALSEFALSE | zainicjowany do opisywania błęduinitialized to describe error |
PrzykładExample
CFile f;
CFileException e;
TCHAR* pszFileName = _T("Open_File.dat");
if(!f.Open(pszFileName, CFile::modeCreate | CFile::modeWrite, &e))
{
TRACE(_T("File could not be opened %d\n"), e.m_cause);
}
//A second example for CFile::Open.
//This function uses CFile to copy binary files.
bool BinaryFileCopy(LPCTSTR pszSource, LPCTSTR pszDest)
{
// constructing these file objects doesn't open them
CFile sourceFile;
CFile destFile;
// we'll use a CFileException object to get error information
CFileException ex;
// open the source file for reading
if (!sourceFile.Open(pszSource,
CFile::modeRead | CFile::shareDenyWrite, &ex))
{
// complain if an error happened
// no need to delete the ex object
TCHAR szError[1024];
ex.GetErrorMessage(szError, 1024);
_tprintf_s(_T("Couldn't open source file: %1024s"), szError);
return false;
}
else
{
if (!destFile.Open(pszDest, CFile::modeWrite |
CFile::shareExclusive | CFile::modeCreate, &ex))
{
TCHAR szError[1024];
ex.GetErrorMessage(szError, 1024);
_tprintf_s(_T("Couldn't open source file: %1024s"), szError);
sourceFile.Close();
return false;
}
BYTE buffer[4096];
DWORD dwRead;
// Read in 4096-byte blocks,
// remember how many bytes were actually read,
// and try to write that many out. This loop ends
// when there are no more bytes to read.
do
{
dwRead = sourceFile.Read(buffer, 4096);
destFile.Write(buffer, dwRead);
}
while (dwRead > 0);
// Close both files
destFile.Close();
sourceFile.Close();
}
return true;
}
CFile:: uchwyt operatoraCFile::operator HANDLE
Użyj tego operatora, aby przekazać dojście do CFile
obiektu do funkcji, takich jak ReadFileEx i GetFileTime , które oczekują HANDLE
.Use this operator to pass a handle to a CFile
object to functions such as ReadFileEx and GetFileTime that expect a HANDLE
.
operator HANDLE() const;
CFile:: ReadCFile::Read
Odczytuje dane do buforu z pliku skojarzonego z CFile
obiektem.Reads data into a buffer from the file associated with the CFile
object.
virtual UINT Read(
void* lpBuf,
UINT nCount);
ParametryParameters
lpBuflpBuf
Wskaźnik do buforu dostarczonego przez użytkownika, który ma otrzymywać dane odczytane z pliku.Pointer to the user-supplied buffer that is to receive the data read from the file.
nCountnCount
Maksymalna liczba bajtów, które mają być odczytywane z pliku.The maximum number of bytes to be read from the file. W przypadku plików w trybie tekstowym pary wierszy powrotu karetki są zliczane jako pojedyncze znaki.For text-mode files, carriage return-line feed pairs are counted as single characters.
Wartość zwracanaReturn Value
Liczba bajtów przesłanych do buforu.The number of bytes transferred to the buffer. Dla wszystkich CFile
klas zwracana wartość może być mniejsza niż nCount , jeśli osiągnięto koniec pliku.For all CFile
classes, the return value may be less than nCount if the end of file was reached.
PrzykładExample
CFile cfile;
cfile.Open(_T("Write_File.dat"), CFile::modeCreate |
CFile::modeReadWrite);
char pbufWrite[100];
memset(pbufWrite, 'a', sizeof(pbufWrite));
cfile.Write(pbufWrite, 100);
cfile.Flush();
cfile.SeekToBegin();
char pbufRead[100];
cfile.Read(pbufRead, sizeof(pbufRead));
ASSERT(0 == memcmp(pbufWrite, pbufRead, sizeof(pbufWrite)));
Aby uzyskać inny przykład, zobacz CFile:: Open.For another example, see CFile::Open.
CFile:: RemoveCFile::Remove
Ta funkcja statyczna usuwa plik określony przez ścieżkę.This static function deletes the file specified by the path.
static void PASCAL Remove(
LPCTSTR lpszFileName,
CAtlTransactionManager* pTM = NULL);
ParametryParameters
lpszFileNamelpszFileName
Ciąg, który jest ścieżką do żądanego pliku.A string that is the path to the desired file. Ścieżka może być względna lub bezwzględna i może zawierać nazwę sieci.The path can be relative or absolute, and can contain a network name.
pTMpTM
Wskaźnik do obiektu CAtlTransactionManagerPointer to CAtlTransactionManager object
UwagiRemarks
Remove
nie można usunąć katalogu.Remove
won't remove a directory.
Remove
Funkcja członkowska zgłasza wyjątek, jeśli połączony plik jest otwarty lub nie można usunąć pliku.The Remove
member function throws an exception if the connected file is open or if the file can't be removed. Ta funkcja jest równoważna z DEL polecenie.This function is equivalent to the DEL command.
PrzykładExample
//example for CFile::Remove
TCHAR* pFileName = _T("Remove_File.dat");
try
{
CFile::Remove(pFileName);
}
catch (CFileException* pEx)
{
TRACE(_T("File %20s cannot be removed\n"), pFileName);
pEx->Delete();
}
CFile:: RenameCFile::Rename
Ta funkcja statyczna zmienia nazwę określonego pliku.This static function renames the specified file.
static void PASCAL Rename(
LPCTSTR lpszOldName,
LPCTSTR lpszNewName,
CAtlTransactionManager* pTM = NULL);
ParametryParameters
lpszOldNamelpszOldName
Stara ścieżka.The old path.
lpszNewNamelpszNewName
Nowa ścieżka.The new path.
pTMpTM
Wskaźnik do obiektu CAtlTransactionManagerPointer to CAtlTransactionManager object
UwagiRemarks
Nie można zmienić nazwy katalogów.Directories can't be renamed. Ta funkcja jest równoważna z poleceniem REN.This function is equivalent to the REN command.
PrzykładExample
TCHAR* pOldName = _T("Oldname_File.dat");
TCHAR* pNewName = _T("Renamed_File.dat");
try
{
CFile::Rename(pOldName, pNewName);
}
catch(CFileException* pEx )
{
TRACE(_T("File %20s not found, cause = %d\n"), pOldName,
pEx->m_cause);
pEx->Delete();
}
CFile:: SeekCFile::Seek
Zmienia położenie wskaźnika pliku w otwartym pliku.Repositions the file pointer in an open file.
virtual ULONGLONG Seek(
LONGLONG lOff,
UINT nFrom);
ParametryParameters
lOfflOff
Liczba bajtów do przeniesienia wskaźnika pliku.Number of bytes to move the file pointer. Wartości dodatnie przesuwają wskaźnik pliku do końca pliku; wartości ujemne przesuwają wskaźnik pliku do początku pliku.Positive values move the file pointer towards the end of the file; negative values move the file pointer towards the start of the file.
NZEnFrom
Pozycja do wyszukania.Position to seek from. Więcej wartości można znaleźć w sekcji uwagi.See the Remarks section for possible values.
Wartość zwracanaReturn Value
Pozycja wskaźnika pliku, jeśli metoda zakończyła się pomyślnie; w przeciwnym razie zwracana wartość jest niezdefiniowana i CFileException
zostanie zgłoszony wskaźnik do wyjątku.The position of the file pointer if the method was successful; otherwise, the return value is undefined and a pointer to a CFileException
exception is thrown.
UwagiRemarks
Poniższa tabela zawiera listę możliwych wartości parametru NZE .The following table lists possible values for the nFrom parameter.
WartośćValue | OpisDescription |
---|---|
CFile::begin |
Wyszukaj od początku pliku.Seek from the start of the file. |
CFile::current |
Wyszukaj w bieżącej lokalizacji wskaźnika pliku.Seek from the current location of the file pointer. |
CFile::end |
Wyszukaj od końca pliku.Seek from the end of the file. |
Gdy plik zostanie otwarty, wskaźnik pliku jest umieszczony na 0, na początku pliku.When a file is opened, the file pointer is positioned at 0, the start of the file.
Można ustawić wskaźnik pliku na pozycję poza końcem pliku.You can set the file pointer to a position beyond the end of a file. Jeśli to zrobisz, rozmiar pliku nie zostanie zwiększony do momentu zapisu w pliku.If you do, the size of the file doesn't increase until you write to the file.
Program obsługi wyjątków dla tej metody musi usunąć obiekt wyjątku po przetworzeniu wyjątku.The exception handler for this method must delete the exception object after the exception is processed.
PrzykładExample
CFile cfile;
cfile.Open(_T("Seek_File.dat"), CFile::modeCreate |
CFile::modeReadWrite);
LONGLONG lOffset = 1000;
ULONGLONG lActual;
lActual = cfile.Seek(lOffset, CFile::begin);
CFile:: SeekToBeginCFile::SeekToBegin
Ustawia wartość wskaźnika pliku na początku pliku.Sets the value of the file pointer to the beginning of the file.
void SeekToBegin();
UwagiRemarks
SeekToBegin()
jest równoważne Seek( 0L, CFile::begin )
.SeekToBegin()
is equivalent to Seek( 0L, CFile::begin )
.
PrzykładExample
CFile f;
f.Open(_T("Seeker_File.dat"), CFile::modeCreate |
CFile::modeReadWrite);
f.SeekToBegin();
ULONGLONG ullEnd = f.SeekToEnd();
CFile:: SeekToEndCFile::SeekToEnd
Ustawia wartość wskaźnika pliku na logiczny koniec pliku.Sets the value of the file pointer to the logical end of the file.
ULONGLONG SeekToEnd();
Wartość zwracanaReturn Value
Długość pliku w bajtach.The length of the file in bytes.
UwagiRemarks
SeekToEnd()
jest równoważne CFile::Seek( 0L, CFile::end )
.SeekToEnd()
is equivalent to CFile::Seek( 0L, CFile::end )
.
PrzykładExample
CFile f;
f.Open(_T("Seeker_File.dat"), CFile::modeCreate |
CFile::modeReadWrite);
f.SeekToBegin();
ULONGLONG ullEnd = f.SeekToEnd();
CFile:: SetFilePathCFile::SetFilePath
Wywołaj tę funkcję, aby określić ścieżkę pliku.Call this function to specify the path of the file. Na przykład jeśli ścieżka pliku nie jest dostępna w przypadku konstruowania obiektu CFile , należy wywołać SetFilePath
go.For example, if the path of a file isn't available when a CFile object is constructed, call SetFilePath
to provide it.
virtual void SetFilePath(LPCTSTR lpszNewName);
ParametryParameters
lpszNewNamelpszNewName
Wskaźnik na ciąg określający nową ścieżkę.Pointer to a string specifying the new path.
UwagiRemarks
Uwaga
SetFilePath
nie otwiera pliku ani nie tworzy pliku; po prostu kojarzy CFile
obiekt z nazwą ścieżki, której można następnie użyć.SetFilePath
does not open the file or create the file; it simply associates the CFile
object with a path name, which can then be used.
PrzykładExample
TCHAR* pstrName = _T("C:\\test\\SetPath_File.dat");
// open a file
HANDLE hFile = ::CreateFile(pstrName, GENERIC_WRITE, FILE_SHARE_READ,
NULL, CREATE_ALWAYS, 0, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
// attach a CFile object to it
CFile myFile(hFile);
// At this point, myFile doesn't know the path name for the file
// it owns because Windows doesn't associate that information
// with the handle. Any CFileExceptions thrown by this object
// won't have complete information.
// Calling SetFilePath() remedies that problem by letting CFile
// know the name of the file that's associated with the object.
myFile.SetFilePath(pstrName);
// write something to the file and flush it immediately
DWORD dwValue = 1234;
myFile.Write(&dwValue, sizeof(dwValue));
myFile.Flush();
// destroying the CObject here will call ::CloseHandle() on the file
}
CFile:: SetLengthCFile::SetLength
Wywołaj tę funkcję, aby zmienić długość pliku.Call this function to change the length of the file.
virtual void SetLength(ULONGLONG dwNewLen);
ParametryParameters
dwNewLendwNewLen
Wymagana długość pliku w bajtach.Desired length of the file in bytes. Ta wartość może być większa lub mniejsza niż bieżąca długość pliku.This value can be larger or smaller than the current length of the file. Plik zostanie rozszerzony lub obcięty zgodnie z potrzebami.The file will be extended or truncated as appropriate.
UwagiRemarks
Uwaga
W programie CMemFile
Ta funkcja może zgłosić CMemoryException
obiekt.With CMemFile
, this function could throw a CMemoryException
object.
PrzykładExample
CFile cfile;
cfile.Open(_T("SetLength_File.dat"), CFile::modeCreate |
CFile::modeReadWrite);
ULONGLONG dwNewLength = 10000;
cfile.SetLength(dwNewLength);
CFile:: SetStatusCFile::SetStatus
Ustawia stan pliku skojarzonego z tą lokalizacją pliku.Sets the status of the file associated with this file location.
static void PASCAL SetStatus(
LPCTSTR lpszFileName,
const CFileStatus& status,
CAtlTransactionManager* pTM = NULL);
ParametryParameters
lpszFileNamelpszFileName
Ciąg, który jest ścieżką do żądanego pliku.A string that is the path to the desired file. Ścieżka może być względna lub bezwzględna i może zawierać nazwę sieci.The path can be relative or absolute, and can contain a network name.
Stanystatus
Bufor zawierający nowe informacje o stanie.The buffer containing the new status information. Wywołaj GetStatus
funkcję członkowską, aby wstępnie wypełnić CFileStatus
strukturę wartościami bieżącymi, a następnie wprowadź zmiany zgodnie z potrzebami.Call the GetStatus
member function to prefill the CFileStatus
structure with current values, then make changes as required. Jeśli wartość wynosi 0, odpowiadający jej element status nie zostanie zaktualizowany.If a value is 0, then the corresponding status item isn't updated. Zapoznaj się z funkcją elementu członkowskiego GetStatus , aby zapoznać się z opisem CFileStatus
struktury.See the GetStatus member function for a description of the CFileStatus
structure.
pTMpTM
Wskaźnik do obiektu CAtlTransactionManagerPointer to CAtlTransactionManager object
UwagiRemarks
Aby ustawić godzinę, zmodyfikuj m_mtime
pole stanu.To set the time, modify the m_mtime
field of status.
W przypadku wywołania do SetStatus
programu przy próbie zmiany tylko atrybutów pliku, a m_mtime
element członkowski struktury stanu pliku jest różny od zera, może to mieć wpływ na atrybuty (zmiana sygnatury czasowej może mieć wpływ na atrybuty).When you make a call to SetStatus
in an attempt to change only the attributes of the file, and the m_mtime
member of the file status structure is nonzero, the attributes may also be affected (changing the time stamp may have side effects on the attributes). Jeśli chcesz zmienić tylko atrybuty pliku, najpierw ustaw m_mtime
element członkowski struktury stanu pliku na zero, a następnie wykonaj wywołanie SetStatus
.If you want to only change the attributes of the file, first set the m_mtime
member of the file status structure to zero and then make a call to SetStatus
.
PrzykładExample
TCHAR* pFileName = _T("ReadOnly_File.dat");
CFileStatus status;
CFile::GetStatus(pFileName, status);
status.m_attribute |= CFile::readOnly;
CFile::SetStatus(pFileName, status);
CFile:: UnlockRangeCFile::UnlockRange
Odblokowuje zakres bajtów w otwartym pliku.Unlocks a range of bytes in an open file.
virtual void UnlockRange(
ULONGLONG dwPos,
ULONGLONG dwCount);
ParametryParameters
dwPosdwPos
Przesunięcie bajtu początku zakresu bajtów do odblokowania.The byte offset of the start of the byte range to unlock.
dwCountdwCount
Liczba bajtów w zakresie do odblokowania.The number of bytes in the range to unlock.
UwagiRemarks
Zobacz opis funkcji elementu członkowskiego LockRange , aby uzyskać szczegółowe informacje.See the description of the LockRange member function for details.
Uwaga
Ta funkcja jest niedostępna dla CMemFile
klasy pochodnej.This function is not available for the CMemFile
-derived class.
PrzykładExample
CFile cfile;
cfile.Open(_T("LockRange_File.dat"), CFile::modeCreate |
CFile::modeReadWrite);
ULONGLONG dwPos = 10;
ULONGLONG dwCount = 100;
cfile.LockRange(dwPos, dwCount);
// do something with the file
cfile.UnlockRange(dwPos, dwCount);
CFile:: WriteCFile::Write
Zapisuje dane z buforu do pliku skojarzonego z CFile
obiektem.Writes data from a buffer to the file associated with the CFile
object.
virtual void Write(
const void* lpBuf,
UINT nCount);
ParametryParameters
lpBuflpBuf
Wskaźnik do buforu dostarczonego przez użytkownika, który zawiera dane, które mają być zapisywane do pliku.A pointer to the user-supplied buffer that contains the data to be written to the file.
nCountnCount
Liczba bajtów, które mają zostać przeniesione z bufora.The number of bytes to be transferred from the buffer. W przypadku plików w trybie tekstowym pary wierszy powrotu karetki są zliczane jako pojedyncze znaki.For text-mode files, carriage return-line feed pairs are counted as single characters.
UwagiRemarks
Write
zgłasza wyjątek w odpowiedzi na kilka warunków, w tym dysk — pełen warunek.Write
throws an exception in response to several conditions, including the disk-full condition.
PrzykładExample
CFile cfile;
cfile.Open(_T("Write_File.dat"), CFile::modeCreate |
CFile::modeReadWrite);
char pbufWrite[100];
memset(pbufWrite, 'a', sizeof(pbufWrite));
cfile.Write(pbufWrite, 100);
cfile.Flush();
Zobacz również przykłady dla CFile:: CFile i CFile:: Open.Also see the examples for CFile::CFile and CFile::Open.
Zobacz teżSee also
Przykład DRAWCLI MFCMFC Sample DRAWCLI
Klasa CObjectCObject Class
Wykres hierarchiiHierarchy Chart
Klasa CStdioFileCStdioFile Class
Klasa CMemFileCMemFile Class