Тема 9
Файл
Ім'я файлу
Діалоги відкриття/запису файлу
Функції роботи з іменами файлів
Приклад
Приклад роботи
Файлові типи і змінні
Відкриття файлу
Закриття файлу
Читання з файлу
Умовні позначення формату
Приклад відкриття файлу
Запис до файлу
Переміщення по файлу 1
Переміщення по файлу 2
Функція кінця файлу
113.69K
Категория: ИнформатикаИнформатика

Файли. Прийоми роботи з файлами

1. Тема 9

1
Тема 9
Файли
Прийоми роботи з файлами

2. Файл

2
Файл
На практиці: файл - іменований блок
інформації, який зберігається на носії
інформації.
В інформатиці: файл - це
впорядкована сукупність даних, що
зберігається на диску і займає
іменовану область зовнішньої пам'яті.

3. Ім'я файлу

3
Ім'я файлу
C:\Program Files\Microsoft Office\Office16\BuildingBlocks.dotx
C: - диск
C:\Program Files\Microsoft Office\Office16 - директорія
C:\Program Files\Microsoft Office\Office16\ - шлях (path)
BuildingBlocks.dotx - власне ім'я файлу
.dotx – розширення файлу (extension)

4. Діалоги відкриття/запису файлу

4
Діалоги відкриття/запису файлу
TOpenDialog
TSaveDialog
Властивості та методи
bool Execute();
UnicodeString FileName;
TFileName FileName;

5. Функції роботи з іменами файлів

5
Функції роботи з іменами файлів
UnicodeString ExtractFilePath(const
System::UnicodeString FileName);
UnicodeString ExtractFileDir(const
System::UnicodeString FileName);
UnicodeString ExtractFileName(const
System::UnicodeString FileName);
UnicodeString ExtractFileExt(const
System::UnicodeString FileName);

6. Приклад

6
Приклад
void __fastcall TForm1::Button2Click(TObject *Sender)
{
if (OpenDialog1->Execute())
{
Memo1->Lines->Append(OpenDialog1->FileName);
Memo1->Lines->Append(ExtractFilePath(OpenDialog1->FileName));
Memo1->Lines->Append(ExtractFileDir(OpenDialog1->FileName));
Memo1->Lines->Append(ExtractFileName(OpenDialog1->FileName));
Memo1->Lines->Append(ExtractFileExt(OpenDialog1->FileName));
}
}

7. Приклад роботи

7
Приклад роботи

8. Файлові типи і змінні

8
Файлові типи і змінні
#include <stdio.h>
FILE *OFile;

9. Відкриття файлу

9
Відкриття файлу
FILE *_wfopen(const wchar_t *filename,
const wchar_t *mode);
Режими (mode) відкриття файлів
Value
Description
r
Open for reading only.
w
Create for writing. If a file by that name already exists, it will be
overwritten.
a
Append; open for writing at end-of-file or create for writing if the
file does not exist.
r+
Open an existing file for update (reading and writing).
w+
Create a new file for update (reading and writing). If a file by that
name already exists, it will be overwritten.
a+
Open for append; open (or create if the file does not exist) for
update at the end of the file.

10. Закриття файлу

10
Закриття файлу
Prototype
int fclose(FILE *stream);

11. Читання з файлу

11
Читання з файлу
int fwscanf(FILE *stream, const
wchar_t *format[, address, ...]);

12. Умовні позначення формату

12
Specifier
Умовні позначення формату
Conventions
single character (%c) This specification reads the next character, including a whitespace
character.
To skip one whitespace character and read the next non-whitespace
character, use %1s.
character array
[W] = width specification . The address argument is a pointer to an array of
(%[W]c)
characters (char arg[W]). The array consists of W elements.
string (%s)
The address argument is a pointer to an array of characters (char arg[]).
The array size must be at least (n+1) bytes, where n = the length of string s
(in characters). A space or newline character terminates the input field. A
null terminator is automatically appended to the string and stored as the
last element in the array.
floating-point
(%e, %E, %f, %g,
and %G)
Floating-point numbers in the input field must conform to the following
generic format: [+/-] ddddddddd [.] dddd [E|e] [+/-] ddd where [item]
indicates that item is optional, and ddd represents digits (decimal, octal, or
hexadecimal). In addition, +INF, -INF, +NAN, and -NAN are recognized as
floating-point numbers. The sign (+ or -) and capitalization are required.
unsigned
A pointer to unsigned character, unsigned integer, or unsigned long
(%d, %i, %o, %x, %D, can be used in any conversion where a pointer to a character, integer, or
%I, %O, %X, %c, %n) long is allowed.

13. Приклад відкриття файлу

13
Приклад відкриття файлу
#include <vector>
…………………………………
typedef std::vector<double>TNvector;
…………………………………
void __fastcall TForm1::Button1Click(TObject *Sender)
{
TNvector YData(0);
TNvector XData(0);
if (OpenDialog1->Execute())
{
FILE *OFile;
if ((OFile = _wfopen(OpenDialog1->FileName.w_str(), L"rt")) == NULL)
{
Memo1->Lines->Append(OpenDialog1->FileName + L" Файл не вдається відкрити.");
return;
}
Memo1->Lines->Append(OpenDialog1->FileName + L" Файл відкритo.");
double fpx, fpy;
while (fwscanf(OFile, L"%lf%lf", &fpx, &fpy) > 0)
{
XData.resize(XData.size() + 1);
YData.resize(YData.size() + 1);
XData[XData.size() - 1] = fpx;
YData[YData.size() - 1] = fpy;
}
Memo1->Lines->Append(OpenDialog1->FileName + L" Файл прочитано.");
fclose(OFile);
}
}

14. Запис до файлу

14
Запис до файлу
int fwprintf(FILE *stream, const wchar_t *format[,
argument, ...]);
template<typename T>
int WriteResArr(const wchar_t * fn_out, T & ia) {
int err = 0;
int len = ia.size();
FILE *OFile;
if ((OFile = _wfopen(fn_out, L"at")) == NULL) {
err = 1; // Файл не вдається відкрити.;
return err;
}
fwprintf(OFile, L"The Data Points:\n");
for (int i = 0; i < len; i++) {
fwprintf(OFile, FloatToStr(ia[i]).w_str());
fwprintf(OFile, L": ");
}
fwprintf(OFile, L"\n");
fclose(OFile);
return err;}

15. Переміщення по файлу 1

15
Переміщення по файлу 1
int fseek(FILE *stream, long offset, int whence);
whence
SEEK_SET
SEEK_CUR
SEEK_END
0 File beginning
•If stream is in binary mode, then fseek sets the file pointer to offset bytes from
the beginning of the file.
•If stream is in text mode, then fseek sets the file pointer according to the offset
value. offset can be either zero (representing the beginning of the file) or a
value returned by an earlier successful call to ftell (representing another
position in the file). The offset value is not a byte count, so you cannot add to it
or subtract from it.
1 Current file pointer position
•If stream is in binary mode, then fseek adds offset to the current file pointer
value.
•If stream is in text mode, then the offset must be zero (leaves the file pointer at
its current value -- keeping the current position in the file.)
2 End-of-file
•If stream is in binary mode, then fseek adds offset bytes from the end of the
file (possibly positioning the file pointer after an arbitrary number of null
characters).
•If stream is in text mode, then the offset must be zero (representing the end of
the file).

16. Переміщення по файлу 2

16
Переміщення по файлу 2
int fseek(FILE *stream, long offset, int whence);
Return value
EBADF
EINVAL
ESPIPE
Bad file pointer
Invalid argument
Illegal seek on devic
long curpos;
FILE *stream;
stream = fopen("MYFILE.TXT", "w+");
fseek(stream, 0L, SEEK_END);
curpos = ftell(stream);
fseek(stream, curpos, SEEK_SET);

17. Функція кінця файлу

17
Функція кінця файлу
int feof(FILE *stream);
Return Value
feof returns nonzero if an end-of-file
indicator was detected on the last input
operation on the named stream and 0 if
end-of-file has not been reached.
English     Русский Правила