include stdio h include stdlib h int main
ПЕРЕНОС ИНФОРМАЦИИ С ФАЙЛА В ФАЙЛ #include <stdio. h> #include <stdlib. h> int main() { FILE *S 1, *S 2; int x, y; system("chcp 1251"); system("cls"); printf("Введите число: "); scanf("%d", &x); S 1 = fopen("S 1. txt", "w"); fprintf(S 1, "%d", x); fclose(S 1); S 1 = fopen("S 1. txt", "r"); S 2 = fopen("S 2. txt", "w"); fscanf(S 1, "%d", &y); y += 3; fclose(S 1); fprintf(S 2, "%dn", y); fclose(S 2); return 0; }
ПРИМЕР ПРОИЗВОЛЬНОГО ДОСТУПА #include <iostream> #include <fstream> using namespace std; int main() { char s[80]; fstream in. Out; in. Out. open("file. txt", ios: : out); in. Out << "строчка текста" << endl; in. Out. seekp(8, ios: : beg); in. Out << "еще строчка текста"; in. Out. close(); in. Out. open("file. txt", ios: : in); in. Out. seekg(-6, ios: : end); in. Out >> s; in. Out. close(); cout << s; cin. get(); return 0; }
ДВОИЧНЫЕ ФАЙЛЫ - ЗАПИСЬ #include <conio. h> #include <stdlib. h> #define ERROR_FILE_OPEN -3 void main() { FILE *output = NULL; int number; output = fopen("D: /c/output. bin", "wb"); if (output == NULL) { printf("Error opening file"); getch(); exit(ERROR_FILE_OPEN); } scanf("%d", &number); fwrite(&number, sizeof(int), 1, output); fclose(output); _getch(); }
ДВОИЧНЫЕ ФАЙЛЫ - ЧТЕНИЕ #include <conio. h> #include <stdlib. h> #define ERROR_FILE_OPEN -3 void main() { FILE *input = NULL; int number; input = fopen("D: /c/output. bin", "rb"); if (input == NULL) { printf("Error opening file"); getch(); exit(ERROR_FILE_OPEN); } fread(&number, sizeof(int), 1, input); printf("%d", number); fclose(input); _getch(); }
ЗАПИСЬ ЧИСЛА И ЧТЕНИЕ ЕГО #include <conio. 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(); }
ФУНКЦИИ УПРАВЛЕНИЯ ПОЗИЦИЕЙ В ДВОИЧНОМ ФАЙЛЕ int fgetpos ( FILE * stream, fpos_t * pos ); int fsetpos ( FILE * stream, const fpos_t * pos );
//ПРИМЕР ИСПОЛЬЗОВАНИЯ ФУНКЦИИ FGETPOS #include <cstdio> #include <iostream> int main() { FILE * ptr. File = fopen ("file. txt", "r"); fpos_t pos; if (ptr. File == NULL) perror ("Ошибка открытия файла"); else { std: : cout << "первый символ: " << (char)fgetc(ptr. File) << "n"; fgetpos (ptr. File, &pos); // получить текущую позицию в файле for (int counter = 0; counter < 4; counter++) { fsetpos (ptr. File, &pos); // изменить позицию std: : cout << "Второй символ: " << (char)fgetc (ptr. File) << "n"; } fclose (ptr. File); // закрыть файл } return 0; }
- Slides: 21