Содержание
Reading and writing to a text file
For reading and writing to a text file, we use the functions and
They are just the file versions of and . The only difference is that and expects a pointer to the structure FILE.
Example 1: Write to a text file
This program takes a number from the user and stores in the file .
After you compile and run this program, you can see a text file created in C drive of your computer. When you open the file, you can see the integer you entered.
Example 2: Read from a text file
This program reads the integer present in the file and prints it onto the screen.
If you successfully created the file from Example 1, running this program will get you the integer you entered.
Other functions like , etc. can be used in a similar way.
fseek
Одной из важных функций для работы с бинарными файлами является функция fseek
int fseek ( FILE * stream, long int offset, int origin );
Эта функция устанавливает указатель позиции, ассоциированный с потоком, на новое положение. Индикатор позиции указывает, на каком месте в файле мы остановились. Когда мы открываем файл, позиция равна 0. Каждый раз, записывая байт данных, указатель позиции сдвигается на единицу вперёд.
fseek принимает в качестве аргументов указатель на поток и сдвиг в offset байт относительно origin. origin может принимать три значения
- SEEK_SET — начало файла
- SEEK_CUR — текущее положение файла
- SEEK_END — конец файла. К сожалению, стандартом не определено, что такое конец файла, поэтому полагаться на эту функцию нельзя.
В случае удачной работы функция возвращает 0.
Дополним наш старый пример: запишем число, затем сдвинемся указатель на начало файла и прочитаем его.
#include <conio.h> #include <stdio.h> #include <stdlib.h> #define ERROR_FILE_OPEN -3 void main() { FILE *iofile = NULL; int number; iofile = fopen("D:/c/output.bin", "w+b"); if (iofile == NULL) { printf("Error opening file"); getch(); exit(ERROR_FILE_OPEN); } scanf("%d", &number); fwrite(&number, sizeof(int), 1, iofile); fseek(iofile, 0, SEEK_SET); number = 0; fread(&number, sizeof(int), 1, iofile); printf("%d", number); fclose(iofile); _getch(); }
Вместо этого можно также использовать функцию rewind, которая перемещает индикатор позиции в начало.
В си определён специальный тип fpos_t, который используется для хранения позиции индикатора позиции в файле.
Функция
int fgetpos ( FILE * stream, fpos_t * pos );
используется для того, чтобы назначить переменной pos текущее положение. Функция
int fsetpos ( FILE * stream, const fpos_t * pos );
используется для перевода указателя в позицию, которая хранится в переменной pos. Обе функции в случае удачного завершения возвращают ноль.
long int ftell ( FILE * stream );
возвращает текущее положение индикатора относительно начала файла. Для бинарных файлов — это число байт, для текстовых не определено (если текстовый файл состоит из однобайтовых символов, то также число байт).
Рассмотрим пример: пользователь вводит числа. Первые 4 байта файла: целое, которое обозначает, сколько чисел было введено. После того, как пользователь прекращает вводить числа, мы перемещаемся в начало файла и записываем туда число введённых элементов.
#include <stdio.h> #include <conio.h> #include <stdlib.h> #define ERROR_OPEN_FILE -3 void main() { FILE *iofile = NULL; unsigned counter = 0; int num; int yn; iofile = fopen("D:/c/numbers.bin", "w+b"); if (iofile == NULL) { printf("Error opening file"); getch(); exit(ERROR_OPEN_FILE); } fwrite(&counter, sizeof(int), 1, iofile); do { printf("enter new number? "); scanf("%d", &yn); if (yn == 1) { scanf("%d", &num); fwrite(&num, sizeof(int), 1, iofile); counter++; } else { rewind(iofile); fwrite(&counter, sizeof(int), 1, iofile); break; } } while(1); fclose(iofile); getch(); }
Вторая программа сначала считывает количество записанных чисел, а потом считывает и выводит числа по порядку.
#include <stdio.h> #include <conio.h> #include <stdlib.h> #define ERROR_OPEN_FILE -3 void main() { FILE *iofile = NULL; unsigned counter; int i, num; iofile = fopen("D:/c/numbers.bin", "rb"); if (iofile == NULL) { printf("Error opening file"); getch(); exit(ERROR_OPEN_FILE); } fread(&counter, sizeof(int), 1, iofile); for (i = 0; i < counter; i++) { fread(&num, sizeof(int), 1, iofile); printf("%d\n", num); } fclose(iofile); getch(); }
Reading data from a File
There are three different functions dedicated to reading data from a file
- fgetc(file_pointer): It returns the next character from the file pointed to by the file pointer. When the end of the file has been reached, the EOF is sent back.
- fgets(buffer, n, file_pointer): It reads n-1 characters from the file and stores the string in a buffer in which the NULL character ‘\0’ is appended as the last character.
- fscanf(file_pointer, conversion_specifiers, variable_adresses): It is used to parse and analyze data. It reads characters from the file and assigns the input to a list of variable pointers variable_adresses using conversion specifiers. Keep in mind that as with scanf, fscanf stops reading a string when space or newline is encountered.
The following program demonstrates reading from fputs_test.txt file using fgets(),fscanf() and fgetc () functions respectively :
#include <stdio.h> int main() { FILE * file_pointer; char buffer, c; file_pointer = fopen("fprintf_test.txt", "r"); printf("----read a line----\n"); fgets(buffer, 50, file_pointer); printf("%s\n", buffer); printf("----read and parse data----\n"); file_pointer = fopen("fprintf_test.txt", "r"); //reset the pointer char str1, str2, str3, str4; fscanf(file_pointer, "%s %s %s %s", str1, str2, str3, str4); printf("Read String1 |%s|\n", str1); printf("Read String2 |%s|\n", str2); printf("Read String3 |%s|\n", str3); printf("Read String4 |%s|\n", str4); printf("----read the entire file----\n"); file_pointer = fopen("fprintf_test.txt", "r"); //reset the pointer while ((c = getc(file_pointer)) != EOF) printf("%c", c); fclose(file_pointer); return 0; }
Result:
----read a line---- Learning C with Guru99 ----read and parse data---- Read String1 |Learning| Read String2 |C| Read String3 |with| Read String4 |Guru99| ----read the entire file---- Learning C with Guru99
- In the above program, we have opened the file called «fprintf_test.txt» which was previously written using fprintf() function, and it contains «Learning C with Guru99» string. We read it using the fgets() function which reads line by line where the buffer size must be enough to handle the entire line.
- We reopen the file to reset the pointer file to point at the beginning of the file. Create various strings variables to handle each word separately. Print the variables to see their contents. The fscanf() is mainly used to extract and parse data from a file.
- Reopen the file to reset the pointer file to point at the beginning of the file. Read data and print it from the file character by character using getc() function until the EOF statement is encountered
- After performing a reading operation file using different variants, we again closed the file using the fclose function.
Writing a File
Following is the simplest function to write individual characters to a stream −
int fputc( int c, FILE *fp );
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 −
int fputs( const char *s, FILE *fp );
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.
#include <stdio.h> main() { FILE *fp; fp = fopen("/tmp/test.txt", "w+"); fprintf(fp, "This is testing for fprintf...\n"); fputs("This is testing for fputs...\n", fp); fclose(fp); }
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.
File Position Pointers
Both istream and ostream provide member functions for repositioning the file-position pointer. These member functions are seekg («seek get») for istream and seekp («seek put») for ostream.
The argument to seekg and seekp normally is a long integer. A second argument can be specified to indicate the seek direction. The seek direction can be ios::beg (the default) for positioning relative to the beginning of a stream, ios::cur for positioning relative to the current position in a stream or ios::end for positioning relative to the end of a stream.
The file-position pointer is an integer value that specifies the location in the file as a number of bytes from the file’s starting location. Some examples of positioning the «get» file-position pointer are −
// position to the nth byte of fileObject (assumes ios::beg) fileObject.seekg( n ); // position n bytes forward in fileObject fileObject.seekg( n, ios::cur ); // position n bytes back from end of fileObject fileObject.seekg( n, ios::end ); // position at end of fileObject fileObject.seekg( 0, ios::end );
Previous Page Print Page
Next Page
About This Article
JL Written by: Tech Specialist This article was written by Jack Lloyd. Jack Lloyd is a Technology Writer and Editor for wikiHow. He has over two years of experience writing and editing technology-related articles. He is technology enthusiast and an English teacher. This article has been viewed 741,300 times.
How helpful is this? Co-authors: 22 Updated: June 9, 2020 Views: 741,300
Categories: PHP
To open a PHP file on Windows, search online for Notepad++, which is a free text-editor, and download it to your computer. Once it’s finished downloading, double-click the setup file and follow the prompts to install it. After it’s installed, open Notepad++. Then, click «File» and «Open» and locate your PHP file from the file explorer. To open a PHP file on a Mac, search online for BBEdit and download it. Double-click the downloaded DMG file and drag the BBEdit icon to your “Applications” folder. When it’s finished copying, open the program from your applications. Then, click “File” and “Open” and select your PHP file from the finder window. For more tips, including how to print a PHP file, read on!
Did this summary help you?YesNo
Español:abrir un archivo PHP
Português:Abrir um Arquivo PHP
Italiano:Aprire un File PHP
Русский:открыть PHP файл
Français:ouvrir un fichier PHP
Deutsch:Eine PHP Datei aufmachen
ไทย:เปิดไฟล์ PHP
Tiếng Việt:Mở tập tin PHP
Nederlands:Een php‐bestand openen
Bahasa Indonesia:Membuka Berkas PHP
العربية:فتح ملف بي اتش بي
हिन्दी:पीएचपी (PHP) फ़ाइल खोलें (Open a PHP File)
日本語:PHPファイルを開く
Türkçe:Bir PHP Dosyası Nasıl Açılır
中文:打开PHP文件
한국어:PHP 파일 여는 방법
PHP readfile() Function
The function reads a file and writes it to the output buffer.
Assume we have a text file called «webdictionary.txt», stored on the server, that looks like this:
AJAX = Asynchronous JavaScript and XMLCSS = Cascading Style Sheets HTML = Hyper Text Markup LanguagePHP = PHP Hypertext PreprocessorSQL = Structured Query LanguageSVG = Scalable Vector GraphicsXML = EXtensible Markup Language
The PHP code to read the file and write it to the output buffer is as follows (the function returns the number of bytes read on success):
Example
<?phpecho readfile(«webdictionary.txt»);?>
The function is useful if all you want to do is open up a file and read its contents.
The next chapters will teach you more about file handling.
PHP Filesystem Functions
Function | Description |
---|---|
basename() | Returns the filename component of a path |
chgrp() | Changes the file group |
chmod() | Changes the file mode |
chown() | Changes the file owner |
clearstatcache() | Clears the file status cache |
copy() | Copies a file |
delete() | See unlink() |
dirname() | Returns the directory name component of a path |
disk_free_space() | Returns the free space of a filesystem or disk |
disk_total_space() | Returns the total size of a filesystem or disk |
diskfreespace() | Alias of disk_free_space() |
fclose() | Closes an open file |
feof() | Checks if the «end-of-file» (EOF) has been reached for an open file |
fflush() | Flushes buffered output to an open file |
fgetc() | Returns a single character from an open file |
fgetcsv() | Returns a line from an open CSV file |
fgets() | Returns a line from an open file |
fgetss() | Deprecated from PHP 7.3. Returns a line from an open file — stripped from HTML and PHP tags |
file() | Reads a file into an array |
file_exists() | Checks whether or not a file or directory exists |
file_get_contents() | Reads a file into a string |
file_put_contents() | Writes data to a file |
fileatime() | Returns the last access time of a file |
filectime() | Returns the last change time of a file |
filegroup() | Returns the group ID of a file |
fileinode() | Returns the inode number of a file |
filemtime() | Returns the last modification time of a file |
fileowner() | Returns the user ID (owner) of a file |
fileperms() | Returns the file’s permissions |
filesize() | Returns the file size |
filetype() | Returns the file type |
flock() | Locks or releases a file |
fnmatch() | Matches a filename or string against a specified pattern |
fopen() | Opens a file or URL |
fpassthru() | Reads from the current position in a file — until EOF, and writes the result to the output buffer |
fputcsv() | Formats a line as CSV and writes it to an open file |
fputs() | Alias of fwrite() |
fread() | Reads from an open file (binary-safe) |
fscanf() | Parses input from an open file according to a specified format |
fseek() | Seeks in an open file |
fstat() | Returns information about an open file |
ftell() | Returns the current position in an open file |
ftruncate() | Truncates an open file to a specified length |
fwrite() | Writes to an open file (binary-safe) |
glob() | Returns an array of filenames / directories matching a specified pattern |
is_dir() | Checks whether a file is a directory |
is_executable() | Checks whether a file is executable |
is_file() | Checks whether a file is a regular file |
is_link() | Checks whether a file is a link |
is_readable() | Checks whether a file is readable |
is_uploaded_file() | Checks whether a file was uploaded via HTTP POST |
is_writable() | Checks whether a file is writable |
is_writeable() | Alias of is_writable() |
lchgrp() | Changes the group ownership of a symbolic link |
lchown() | Changes the user ownership of a symbolic link |
link() | Creates a hard link |
linkinfo() | Returns information about a hard link |
lstat() | Returns information about a file or symbolic link |
mkdir() | Creates a directory |
move_uploaded_file() | Moves an uploaded file to a new location |
parse_ini_file() | Parses a configuration file |
parse_ini_string() | Parses a configuration string |
pathinfo() | Returns information about a file path |
pclose() | Closes a pipe opened by popen() |
popen() | Opens a pipe |
readfile() | Reads a file and writes it to the output buffer |
readlink() | Returns the target of a symbolic link |
realpath() | Returns the absolute pathname |
realpath_cache_get() | Returns realpath cache entries |
realpath_cache_size() | Returns realpath cache size |
rename() | Renames a file or directory |
rewind() | Rewinds a file pointer |
rmdir() | Removes an empty directory |
set_file_buffer() | Alias of stream_set_write_buffer(). Sets the buffer size for write operations on the given file |
stat() | Returns information about a file |
symlink() | Creates a symbolic link |
tempnam() | Creates a unique temporary file |
tmpfile() | Creates a unique temporary file |
touch() | Sets access and modification time of a file |
umask() | Changes file permissions for files |
unlink() | Deletes a file |
RemarksRemarks
Функция fopen открывает файл, указанный параметром filename.The fopen function opens the file that is specified by filename. По умолчанию строка с узким именем интерпретируется с использованием кодовой страницы ANSI (CP_ACP).By default, a narrow filename string is interpreted using the ANSI codepage (CP_ACP). В классических приложениях Windows эту страницу можно изменить на кодовую страницу OEM (CP_OEMCP) с помощью функции SetFileApisToOEM .In Windows Desktop applications this can be changed to the OEM codepage (CP_OEMCP) by using the SetFileApisToOEM function. С помощью функции AreFileApisANSI можно определить, интерпретируется ли имя файла с использованием ANSI или системной кодовой страницы OEM по умолчанию.You can use the AreFileApisANSI function to determine whether filename is interpreted using the ANSI or the system default OEM codepage. _wfopen — это версия fopenс расширенными символами; аргументы для _wfopen являются строками расширенных символов._wfopen is a wide-character version of fopen; the arguments to _wfopen are wide-character strings. В противном случае _wfopen и fopen работают одинаково.Otherwise, _wfopen and fopen behave identically. Простое использование _wfopen не влияет на закодированную кодировку, используемую в файловом потоке.Just using _wfopen does not affect the coded character set that is used in the file stream.
fopen принимает пути, допустимые в файловой системе в момент выполнения. fopen принимает UNC-пути и пути, которые используют сопоставленные сетевые диски, если система, в которой выполняется код, имеет доступ к общей папке или подключенному диску во время выполнения.fopen accepts paths that are valid on the file system at the point of execution; fopen accepts UNC paths and paths that involve mapped network drives as long as the system that executes the code has access to the share or mapped drive at the time of execution. При создании путей для fopenубедитесь, что диски, пути или сетевые папки будут доступны в среде выполнения.When you construct paths for fopen, make sure that drives, paths, or network shares will be available in the execution environment. В пути в качестве разделителей каталогов можно использовать прямую (/) или обратную (\) косую черту.You can use either forward slashes (/) or backslashes (\) as the directory separators in a path.
Всегда проверяйте возвращаемое значение, чтобы узнать, равен ли указатель NULL, прежде чем выполнять какие-либо дальнейшие операции с файлом.Always check the return value to see whether the pointer is NULL before you perform any additional operations on the file. При возникновении ошибки устанавливается глобальная переменная со значением « No », которую можно использовать для получения конкретных сведений об ошибке.If an error occurs, the global variable errno is set and may be used to obtain specific error information. Дополнительные сведения см. в разделе errno, _doserrno, _sys_errlist и _sys_nerr.For more information, see errno, _doserrno, _sys_errlist, and _sys_nerr.
По умолчанию глобальное состояние этой функции ограничивается приложением.By default, this function’s global state is scoped to the application. Чтобы изменить это, см. раздел глобальное состояние в CRT.To change this, see Global state in the CRT.
Modes to Open Files
When you use fopen PHP methods, you can open files in different modes. They can either be accessible for reading or ready to be modified. There are eight modes in total: r, r+, w, w+, a, a+, x, and x+. Let’s break them down:
- r mode opens a file in read-only mode. The cursor is placed in the beginning of it by default. r+ acts almost the same, but you can both read the file and write in it.
- w mode opens a file as write-only. The cursor is again placed in the beginning automatically. w+ performs the same, but also allows to PHP read the file.
- a opens a file in write-only mode as well, but the cursor is now placed at the end. a+ acts almost the same, but you can both read the file and write in it. If the file is not found, both modes create a new one.
- x is used for creating new files. They appear having a write-only mode (choose x+, if you wish to also be able to read it). If a file with such name is found, the function fails and returns False.
And that’s about it! If it is still a bit unclear to you how to open a PHP file that contains the code itself, we’d recommend reading a lesson on how to install PHP: it has useful tips for the beginners and recommends some systems for a smooth start.
PHP Open File — fopen()
A better method to open files is with the function. This function gives you more options than the function.
We will use the text file, «webdictionary.txt», during the lessons:
AJAX = Asynchronous JavaScript and XMLCSS = Cascading Style Sheets HTML = Hyper Text Markup LanguagePHP = PHP Hypertext PreprocessorSQL = Structured Query LanguageSVG = Scalable Vector GraphicsXML = EXtensible Markup Language
The first parameter of contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened. The following example also generates a message if the fopen() function is unable to open the specified file:
Example
<?php$myfile = fopen(«webdictionary.txt», «r») or die(«Unable to open file!»);echo fread($myfile,filesize(«webdictionary.txt»)); fclose($myfile);?>
Tip: The and the functions will be explained below.
The file may be opened in one of the following modes:
Modes | Description |
---|---|
r | Open a file for read only. File pointer starts at the beginning of the file |
w | Open a file for write only. Erases the contents of the file or creates a new file if it doesn’t exist. File pointer starts at the beginning of the file |
a | Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist |
x | Creates a new file for write only. Returns FALSE and an error if file already exists |
r+ | Open a file for read/write. File pointer starts at the beginning of the file |
w+ | Open a file for read/write. Erases the contents of the file or creates a new file if it doesn’t exist. File pointer starts at the beginning of the file |
a+ | Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist |
x+ | Creates a new file for read/write. Returns FALSE and an error if file already exists |
Types of Files
When dealing with files, there are two types of files you should know about:
- Text files
- Binary files
1. Text files
Text files are the normal .txt files. You can easily create text files using any simple text editors such as Notepad.
When you open those files, you’ll see all the contents within the file as plain text. You can easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide the least security and takes bigger storage space.
2. Binary files
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0’s and 1’s).
They can hold a higher amount of data, are not readable easily, and provides better security than text files.
С этим читают