Read file program c windows

C — File I/O

The last chapter explained the standard input and output devices handled by C programming language. This chapter cover how C programmers can create, open, close text or binary files for their data storage.

A file represents a sequence of bytes, regardless of it being a text file or a binary file. C programming language provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices. This chapter will take you through the important calls for file management.

Opening Files

You can use the fopen( ) function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream. The prototype of this function call is as follows −

Here, filename is a string literal, which you will use to name your file, and access mode can have one of the following values −

Opens an existing text file for reading purpose.

Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file.

Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content.

Opens a text file for both reading and writing.

Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist.

Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.

If you are going to handle binary files, then you will use following access modes instead of the above mentioned ones −

Closing a File

To close a file, use the fclose( ) function. The prototype of this function is −

The fclose(-) function returns zero on success, or EOF if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.

There are various functions provided by C standard library to read and write a file, character by character, or in the form of a fixed length string.

Writing a File

Following is the simplest function to write individual characters to a stream −

The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream −

The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char *format, . ) function as well to write a string into a file. Try the following example.

Make sure you have /tmp directory available. If it is not, then before proceeding, you must create this directory on your machine.

When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in the next section.

Reading a File

Given below is the simplest function to read a single character from a file −

The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error, it returns EOF. The following function allows to read a string from a stream −

The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string.

If this function encounters a newline character ‘\n’ or the end of the file EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including the new line character. You can also use int fscanf(FILE *fp, const char *format, . ) function to read strings from a file, but it stops reading after encountering the first space character.

When the above code is compiled and executed, it reads the file created in the previous section and produces the following result −

Let’s see a little more in detail about what happened here. First, fscanf() read just This because after that, it encountered a space, second call is for fgets() which reads the remaining line till it encountered end of line. Finally, the last call fgets() reads the second line completely.

Binary I/O Functions

There are two functions, that can be used for binary input and output −

Both of these functions should be used to read or write blocks of memories — usually arrays or structures.

How to read the small memory dump file that is created by Windows if a crash occurs

This article describes how to examine a small memory dump file. A small memory dump file can help you determine why your computer crashed.

Original product version: В Windows 10 — all editions, Windows Server 2012 R2
Original KB number: В 315263

If you are looking for debug information for Windows 8 or later, please check Debugging Tools for Windows (WinDbg, KD, CDB, NTSD). For more information about small memory dump, please check Small Memory Dump.

Small memory dump files

If your computer crashes, how can you find out what happened, fix the issue and it prevent it from happening again? You may find the small memory dump file useful in this situation. The small memory dump file contains the smallest amount of useful information that could help you identify why your computer crashed. The memory dump file contains the following information:

  • The Stop message, its parameters, and other data
  • A list of loaded drivers
  • The processor context (PRCB) for the processor that stopped
  • The process information and kernel context (EPROCESS) for the process that stopped
  • The process information and kernel context (ETHREAD) for the thread that stopped
  • The Kernel-mode call stack for the thread that stopped

To create a memory dump file, Windows requires a paging file on the boot volume that is at least 2 megabytes (MB) in size. On computers that are running Microsoft Windows 2000, or a later version of Windows, a new memory dump file is created each time that a computer crash may occur. A history of these files is stored in a folder. If a second problem occurs and if Windows creates a second small memory dump file, Windows preserves the previous file. Windows gives each file a distinct, date-encoded file name. For example, Mini022900-01.dmp is the first memory dump file that was generated on February 29, 2000. Windows keeps a list of all the small memory dump files in the %SystemRoot%\Minidump folder.

The small memory dump file can be useful when hard disk space is limited. However, because of the limited information that is included, errors that were not directly caused by the thread that was running at the time of the problem may not be discovered by an analysis of this file.

Configure the dump type

To configure startup and recovery options to use the small memory dump file, follow these steps.

Because there are several versions of Microsoft Windows, the following steps may be different on your computer. If they are, see your product documentation to complete these steps.

Click Start, and then click Control Panel.

Double-click System, and then click Advanced system settings.

Click the Advanced tab, and then click Settings under Startup and Recovery.

In the Write debugging information list, click Small memory dump (64k).

To change the folder location for the small memory dump files, type a new path in the Dump File box or in the Small dump directory box, depending on your version of Windows).

Tools to read the small memory dump file

Use the Dump Check Utility (Dumpchk.exe) to read a memory dump file or verify that the file has been created correctly.

The Dump Check Utility does not require access to debugging symbols. Symbol files hold a variety of data which are not actually needed when running the binaries, but which could be very useful in the debugging process.

For more information about how to use Dump Check Utility in Windows NT, Windows 2000, Windows Server 2003 or Windows Server 2008, see Microsoft Knowledge Base article 156280: How to Use Dumpchk.exe to check a memory dump file.

For more information about how to use Dump Check Utility in Windows XP, Windows Vista or Windows 7, see Microsoft Knowledge Base article 315271: How to use Dumpchk.exe to check a Memory Dump file.

Or, you can use the Windows Debugger (WinDbg.exe) tool or the Kernel Debugger (KD.exe) tool to read small memory dump files. WinDbg and KD.exe are included with the latest version of the Debugging Tools for Windows package.

To install the debugging tools, see the Download and Install Debugging Tools for Windows webpage. Select the Typical installation. By default, the installer installs the debugging tools in the following folder:

C:\Program Files\Debugging Tools for Windows

This Web page also provides access to the downloadable symbol packages for Windows. For more information about Windows symbols, see Debugging with Symbols, and the Download Windows Symbol Packages webpage.

For more information about dump file options in Windows, see Overview of memory dump file options for Windows.

Open the dump file

To open the dump file after the installation is complete, follow these steps:

Click Start, click Run, type cmd , and then click OK.

Change to the Debugging Tools for Windows folder. To do this, type the following at the command prompt, and then press ENTER:

To load the dump file into a debugger, type one of the following commands, and then press ENTER:

The following table explains the use of the placeholders that are used in these commands.

Sr.No. Mode & Description
1
Placeholder Explanation
SymbolPath Either the local path where the symbol files have been downloaded or the symbol server path, including a cache folder. Because a small memory dump file contains limited information, the actual binary files must be loaded together with the symbols for the dump file to be correctly read.
ImagePath The path of these files. The files are contained in the I386 folder on the Windows XP CD-ROM. For example, the path may be C:\Windows\I386 .
DumpFilePath The path and file name for the dump file that you are examining.

Sample commands

You can use the following sample commands to open the dump file. These commands assume the following:

  • The contents of the I386 folder on the Windows CD-ROM are copied to the C:\Windows\I386 folder.
  • Your dump file is named C:\Windows\Minidump\Minidump.dmp .

Sample 2. If you prefer the graphical version of the debugger instead of the command-line version, type the following command instead:

Examine the dump file

There are several commands that you can use to gather information in the dump file, including the following commands:

  • The !analyze -show command displays the Stop error code and its parameters. The Stop error code is also known as the bug check code.
  • The !analyze -v command displays verbose output.
  • The lm N T command lists the specified loaded modules. The output includes the status and the path of the module.

The !drivers extension command displays a list of all drivers that are loaded on the destination computer, together with summary information about their memory use. The !drivers extension is obsolete in Windows XP and later. To display information about loaded drivers and other modules, use the lm command. The lm N T command displays information in a format that is similar to the old !drivers extension.

For help with other commands and for complete command syntax, see the debugging tools Help documentation. The debugging tools Help documentation can be found in the following location:

C:\Program Files\Debugging Tools for Windows\Debugger.chm

If you have symbol-related issues, use the Symchk utility to verify that the correct symbols are loaded correctly. For more information about how to use Symchk, see Debugging with Symbols.

Simplify the commands by using a batch file

After you identify the command that you must have to load memory dumps, you can create a batch file to examine a dump file. For example, create a batch file and name it Dump.bat. Save it in the folder where the debugging tools are installed. Type the following text in the batch file:

When you want to examine a dump file, type the following command to pass the dump file path to the batch file:

Создание, запись и чтение файла Create, write, and read a file

Важные API Important APIs

Считайте и запишите файл с помощью объекта StorageFile. Read and write a file using a StorageFile object.

Полный пример: пример доступа к файлам. For a complete sample, see the File access sample.

Необходимые компоненты Prerequisites

Общее представление об асинхронном программировании для приложений универсальной платформы Windows (UWP) . Understand async programming for Universal Windows Platform (UWP) apps

Описание процесса написания асинхронных приложений на C# или Visual Basic см. в статье Вызов асинхронных API в C# и Visual Basic. You can learn how to write asynchronous apps in C# or Visual Basic, see Call asynchronous APIs in C# or Visual Basic. Чтобы узнать, как создавать асинхронные приложения с помощью C++/WinRT, ознакомьтесь с разделом Параллельная обработка и асинхронные операции с помощью C++/WinRT. To learn how to write asynchronous apps in C++/WinRT, see Concurrency and asynchronous operations with C++/WinRT. Чтобы узнать, как создавать асинхронные приложения на C++/CX, ознакомьтесь с разделом Асинхронное программирование на языке C++/CX. To learn how to write asynchronous apps in C++/CX, see Asynchronous programming in C++/CX.

Знание порядка вызова файла для считывания, записи или выполнения обеих этих операций. Know how to get the file that you want to read from, write to, or both

Сведения о вызове файла с помощью средства выбора файлов см. в разделе Открытие файлов и папок с помощью средства выбора. You can learn how to get a file by using a file picker in Open files and folders with a picker.

Создание файла Creating a file

Ниже приведен порядок создания файла в локальной папке приложения. Here’s how to create a file in the app’s local folder. Заменим его, если он уже существует. If it already exists, we replace it.

Запись в файл Writing to a file

Ниже приведен порядок записи в доступный для записи файл на диске с помощью класса StorageFile. Here’s how to write to a writable file on disk using the StorageFile class. Первое действие для каждого из способов записи в файл (если запись в файл происходит не сразу же после его создания) — это получение файла с помощью StorageFolder.GetFileAsync. The common first step for each of the ways of writing to a file (unless you’re writing to the file immediately after creating it) is to get the file with StorageFolder.GetFileAsync.

Запись текста в файл Writing text to a file

Запишите текст в файл, вызвав метод FileIO.WriteTextAsync. Write text to your file by calling the FileIO.WriteTextAsync method.

Запись байтов в файл с использованием буфера (2 действия) Writing bytes to a file by using a buffer (2 steps)

Сначала вызовите CryptographicBuffer.ConvertStringToBinary для получения буфера байтов (на основе строки), которые требуется записать в файл. First, call CryptographicBuffer.ConvertStringToBinary to get a buffer of the bytes (based on a string) that you want to write to your file.

Затем запишите байты из буфера в файл, вызвав метод FileIO.WriteBufferAsync. Then write the bytes from your buffer to your file by calling the FileIO.WriteBufferAsync method.

Запись текста в файл с использованием потока (4 действия) Writing text to a file by using a stream (4 steps)

Сначала откройте файл, вызвав метод StorageFile.OpenAsync. First, open the file by calling the StorageFile.OpenAsync method. По завершении операции открытия будет возвращен поток содержимого файла. It returns a stream of the file’s content when the open operation completes.

Далее получите выходной поток, вызвав метод IRandomAccessStream.GetOutputStreamAt из stream . Next, get an output stream by calling the IRandomAccessStream.GetOutputStreamAt method from the stream . Если вы используете C#, вставьте его в оператор using, чтобы управлять временем существования выходного потока. If you’re using C#, then enclose this in a using statement to manage the output stream’s lifetime. Если вы используете C++/WinRT, то можете контролировать его время существования, заключив его в блок или задав значение nullptr по завершении. If you’re using C++/WinRT, then you can control its lifetime by enclosing it in a block, or setting it to nullptr when you’re done with it.

Теперь добавьте этот код (если вы используете C#, то в существующий оператор using) для записи в поток вывода, создав новый объект DataWriter и вызвав метод DataWriter.WriteString. Now add this code (if you’re using C#, within the existing using statement) to write to the output stream by creating a new DataWriter object and calling the DataWriter.WriteString method.

Наконец, добавьте этот код (если вы используете C#, то во внутренний оператор using) для сохранения текста в файл с помощью DataWriter.StoreAsync и закрытия потока с помощью IOutputStream.FlushAsync. Lastly, add this code (if you’re using C#, within the inner using statement) to save the text to your file with DataWriter.StoreAsync and close the stream with IOutputStream.FlushAsync.

Рекомендации по записи в файл Best practices for writing to a file

Дополнительные сведения и рекомендации см. в разделе Рекомендации по записи в файлы. For additional details and best practice guidance, see Best practices for writing to files.

Чтение из файла Reading from a file

Ниже приведен порядок чтения из файла на диске с помощью класса StorageFile. Here’s how to read from a file on disk using the StorageFile class. Первое действие для каждого из способов чтения из файла — это получение файла с помощью StorageFolder.GetFileAsync. The common first step for each of the ways of reading from a file is to get the file with StorageFolder.GetFileAsync.

Чтение текста из файла Reading text from a file

Чтобы выполнить чтение текста из файла, вызовите метод FileIO.ReadTextAsync. Read text from your file by calling the FileIO.ReadTextAsync method.

Чтение текста из файла с использованием буфера (2 действия) Reading text from a file by using a buffer (2 steps)

Затем используйте объект DataReader, чтобы сначала считать длину буфера, а затем его содержимое. Then use a DataReader object to read first the length of the buffer and then its contents.

Чтение текста из файла с использованием потока (4 действия) Reading text from a file by using a stream (4 steps)

Откройте поток для файла, вызвав метод StorageFile.OpenAsync. Open a stream for your file by calling the StorageFile.OpenAsync method. По завершении операции будет возвращен поток содержимого файла. It returns a stream of the file’s content when the operation completes.

Получите размер потока для последующего использования. Get the size of the stream to use later.

Читайте также:  Cmi8738 c3dx pci audio драйвер windows
Оцените статью