Last active
December 22, 2015 01:32
-
-
Save a1ip/47989320dfa93e007358 to your computer and use it in GitHub Desktop.
Примеры кода из книги "ВВЕДЕНИЕ В ЯЗЫК СИ"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Модуль addt.c | |
//------------------------------------------------------- | |
//Функция Add( ) добавляет строку str в файл tel_num.txt | |
//------------------------------------------------------- | |
void Create(void) //Создает файл, если он не существует | |
{ | |
if ((F_tel = fopen(File, "wb+")) == NULL) | |
{ | |
fprintf(stderr, "\"%s\" : невозможно открыть\n", File); | |
exit(1); | |
} | |
Count = 0; | |
if ( ! fwrite(&Count, sizeof(Count), 1, F_tel)) | |
{ | |
fprintf(stderr, "\"%s\" : ошибка записи\n", File); | |
exit(1); | |
} | |
} | |
void Add(char *s) //Добавляет запись в файл | |
{ | |
char str[MAX_NAME], sn[MAX_NUMBER]; //Временные массивы | |
int i; | |
for (i = 0; i < MAX_NAME; i++) | |
str[i] = ' '; //Пробелы в str | |
strcpy(str, s); //Копирование строки в str | |
if ((F_tel = fopen(File, "rb+")) = = NULL) | |
Create(); //Создаем файл, если он не | |
//существует | |
else if (fread(&Count, sizeof(Count), 1, F_tel) != 1) | |
{ | |
fprintf(stderr, "\"%s\" : ошибка чтения\n", File); | |
exit(1); | |
} | |
printf("Номер телефона : "); //Запрашивается и вводится номер | |
if (gets(Number) == NULL || *Number == '\0') | |
{ | |
fclose(F_tel); | |
return; //Возврат, если номер не введен | |
} | |
//Установка указателя в файле на первую свободную запись | |
if (fseek(F_tel, (long)((MAX_NAME+MAX_NUMBER)*Count), SEEK_CUR)!=0) | |
{ | |
fprintf(stderr, "\"%s\" : ошибка поиска\n", File); | |
exit(1); | |
} | |
fwrite(str, 1, MAX_NAME, F_tel); //Запись в файл фамилии | |
for (i = 0; i < MAX_NUMBER; i++) | |
sn[i] = ' '; //Пробелы в sn[ ] | |
strcpy(sn, Number); //Копирование сроки Number в строку sn | |
fwrite(sn, 1, MAX_NUMBER, F_tel); //Запись в файл номера | |
if (ferror(F_tel)) //Проверка наличия ошибки | |
{ | |
fprintf(stderr, "\"%s\" : ошибка записи\n", File); | |
exit(1); | |
} | |
//Установка указателя в файле на первый байт | |
if (fseek(F_tel, 0L, SEEK_SET) != 0) | |
{ | |
fprintf(stderr, "\"%s\" : ошибка позиционирования\n", File); | |
exit(1); | |
} | |
++Count; //Увеличение числа записей на единицу | |
//Запись Count в файл | |
if (fwrite(&Count, sizeof(int), 1,F_tel) != 1) | |
{ | |
fprintf(stderr, "\"%s\" : ошибка записи\n", File); | |
exit(1); | |
} | |
fclose(F_tel); | |
return; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Модуль choicet.c | |
//---------------------------------------------------------------------- | |
//Функция Choice( ), проверяющая есть ли строка str в файле tel_num.txt | |
//---------------------------------------------------------------------- | |
int Choice(char *str) | |
{ | |
int i; | |
char temp[MAX_NAME + MAX_NUMBER]; | |
if ((F_tel = fopen(File, "r")) == NULL) | |
return 1; //Строки str нет в файле | |
if (fread(&Count, sizeof(int), 1, F_tel) != 1) | |
{ | |
fprintf(stderr, "\"%s\" : ошибка чтения\n", File); | |
exit(1); | |
} | |
for (i = 0; i < Count; i++) | |
{ | |
fread(temp, 1, MAX_NAME + MAX_NUMBER, F_tel); | |
if (ferror(F_tel)) | |
{ | |
fprintf(stderr, "\"%s\" : ошибка чтения\n", File); | |
exit(1); | |
} | |
if (strcmp(str, temp) == 0) | |
{ | |
fclose(F_tel); | |
return 0; //Строка str есть в файле | |
} | |
} | |
fclose(F_tel); | |
return 1; //Строки str нет в файле | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Пример 1 */ | |
#include <stdio.h> | |
void main(void) | |
{ | |
int x, n1, n2; | |
printf("Введите целое число от -32768 до 32767\n"); | |
scanf("%d%n", &x, &n1); | |
printf("x = %d%n\n", x, &n2); | |
printf("n1 = %d, n2 = %d\n", n1, n2); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Пример 2 */ | |
#include <stdio.h> | |
void main(void) | |
{ | |
char str_b[21], str_c[21]; /* Последний элемент резервируем под \0 */ | |
int x, n1, n2; | |
float y; | |
printf("Введите строку до 20 символов\n"); | |
scanf("%s[Computer]%s", str_b, str_c); | |
printf("str_b = %s, str_c = %s\n", str_b, str_c); | |
y = 12.345678; | |
n1 = 8; | |
n2 = 3; | |
x = 0x100; | |
printf("y = %*.*f\n", n1, n2, y); | |
printf("x(16) = %#x, x(16) = %x, x(10) = %i\n", x, x, x); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Пример 3 */ | |
#include <conio.h> | |
#define SYM 'X' /* Выводимый символ */ | |
#define SPACE ' ' /* Определение пробела */ | |
#define LF 10 /* Перевод строки */ | |
#define CR 13 /* Возврат каретки */ | |
#define LEFT 24 /* Левая граница символа */ | |
#define RIGHT 51 /* Правая граница символа */ | |
#define BOTTOM 25 /* Нижняя граница символа */ | |
void main(void) | |
{ | |
int col, line; /* col - номер колонки для вывода символа */ | |
/* line - номер линям для вывода символа */ | |
clrscr( ); | |
for (line = 1; line <= BOTTOM; line++) /* Вывод пробелов до левой | |
границы символа */ | |
{ | |
for (col = 1; col < LEFT; col++) putch(SPACE); | |
for(col = LEFT + 1; col < RIGHT; col++) /* Вывод символа X | |
на весь экран */ | |
if ((col == (LEFT + line)) || (col == (RIGHT - line))) | |
putch(SYM); | |
else putch(SPACE); | |
putch(LF); /* Возврат каретки и перевод строки после */ | |
putch(CR); /* вывода каждой линии символа */ | |
} | |
getch( ); /* Ожидание нажатия клавиши */ | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Пример 4 */ | |
#include <stdio.h> | |
#include <values.h> | |
#include <process.h> | |
long factorial(int value) /* Рекурсивная функция */ | |
{ | |
long result = 1; | |
if (value != 0) | |
{ | |
result = factorial(value - 1); | |
/* Проверка возможности вычисления факториала */ | |
if (result > MAXLONG / (value + 1)) | |
{ | |
fprintf(stderr, "Очень большое число\n"); | |
getch( ); /* Ожидание нажатия клавиши */ | |
exit (1); | |
} | |
result *= value; | |
} | |
return(result); | |
} | |
/* Рекурсивное вычисление факториала числа value */ | |
void main(void) | |
{ | |
int value; /* Факториал этого значения вычисляется */ | |
long result; /* Переменная для результата */ | |
puts("Факториал какого числа?"); | |
scanf("%d", &value); | |
result = factorial(value); | |
printf("Результат: %ld\n", result); | |
getch( ); /* Ожидание нажатия клавиши */ | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Пример 5 */ | |
#include <stdio.h> | |
#include <conio.h> | |
#define ESC 27 /* 27 - ASCII-код клавиши ESC */ | |
void CountOfLines(void) | |
{ | |
/* Статические переменные будут сохранять старые значения при каждом | |
новом вызове функции CountOfLines */ | |
static int words = 0, symbols = 0; /* words-число слов, | |
symbols-число символов */ | |
char temp, t = 0; /* Временные переменные */ | |
++symbols; | |
/* Число символов и слов выдается после нажатия клавиши */ | |
while ((temp = getche( )) != '\r' ) | |
{ | |
++symbols; /* Подсчитывается каждый символ */ | |
/* После одного или нескольких пробелов подсчитывается слово */ | |
if ((temp == ' ') && (t == 1)) continue; | |
if (temp == ' ') { t = 1; ++words; } | |
else t = 0; | |
} | |
if (t == 1) --words; | |
else ++words; | |
printf ("\n Слов: %d; символов: %d\n", words, symbols); | |
} | |
void main(void) | |
{ | |
puts("Для завершения программы нажмите в начале строки"); | |
puts("Строка не должна начинаться с пробела и с нажатия клавиши" | |
""); | |
puts("Строка не должна завершаться пробелом"); | |
while (getche( ) != ESC) CountOfLines(); | |
putch('\b'); | |
putch(' '); | |
putch('\b'); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Модуль findt.c | |
//---------------------------------------------------------- | |
//Функция Find( ) для поиска строки str в файле tel_num.txt | |
//---------------------------------------------------------- | |
void Find(char *str) | |
{ | |
int i; | |
//Если файл невозможно открыть для чтения, то программа | |
//завершает работу | |
if ((F_tel = fopen(File, "r")) == NULL) | |
{ | |
fprintf(stderr, "\"%s\" : невозможно открыть\n", File); | |
exit(1); | |
} | |
//Чтение числа записей (Count) в файле | |
if (fread(&Count, sizeof(int), 1, F_tel) != 1) | |
{ | |
fprintf(stderr, "\"%s\" : ошибка чтения\n", File); | |
exit(1); | |
} | |
//В цикле for осуществляется поиск нужной записи | |
for (i = 1; i < Count; i++) | |
{ | |
fread(Name, 1, MAX_NAME, F_tel); //Чтение имени | |
fread(Number, 1, MAX_NUMBER, F_tel); //Чтение номера | |
if (ferror(F_tel)) //Проверка отсутствия ошибки | |
{ | |
fprintf(stderr, "\"%s\" : ошибка чтения\n'', File); | |
exit(1); | |
} | |
if (strcmp(str, Name) == 0) //Если имя совпадает | |
//с введенным, то фамилия | |
//и найденный номер | |
//выводятся на экран | |
{ | |
printf("Фамилия : %s\n", Name); | |
printf("Номер телефона: %s\n", Number); | |
fclose(F_tel); | |
return; | |
} | |
} | |
//Если результат поиска отрицательный, то выводится | |
//следующее сообщение | |
fprintf(stderr,"\"%s\" : запись в файле отсутствует\n", File); | |
fclose(F_tel); | |
return; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Пример 6 | |
//--------------------------------------------------------- | |
// Головная программа для работы с телефонным справочником | |
//--------------------------------------------------------- | |
#include "A:\my.h" //Заголовочный файл с глобальными | |
//переменными и константами | |
#include "A:\findt.c" //Поиск строки str в файле | |
#include "A:\choicet.c" //Проверка наличия строки в файле | |
#include "A:\addt.c" //Добавление строки в файл | |
#include "A:\subt.c" //Удаление строки из файла | |
void main(int argc, char *argv[ ]) | |
{ | |
if (argc == 3) | |
if (*argv[1] == '+') //Добавить запись | |
{ | |
if (Choice(argv[2]) == 0) //Нет ли такой | |
//записи в файле? | |
{ | |
puts("Эта фамилия есть в справочнике"); | |
exit(1); | |
} | |
Add(argv[2]); //Добавление записи | |
} | |
else if (*argv[1] == '-') Sub(argv[2]); //Удалить запись | |
else puts("Ошибочное значение аргумента"); | |
else if (argc == 2) Find(argv[1]); //Поиск записи | |
else puts("Ошибочное число аргументов"); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Файл заголовков my.h | |
//-------------------------------------------------------- | |
//Определения глобальных переменных и символьных значений | |
//-------------------------------------------------------- | |
#include <stdio.h> | |
#include <process.h> | |
#include <string.h> | |
#define MAX_NAME 20 //Максимальное число символов в фамилии | |
#define MAX_NUMBER 10 //Максимальное число цифр в телеф. номере | |
char Name[MAX_NAME]; //Массив фамилий | |
char Number[MAX_NUMBER]; //Массив для телефонного номера | |
char File[ ] = "A:\\tel\\tel_num.txt"; //Имя файла справочника | |
int Count; //Число фамилий в справочнике | |
FILE *F_tel; //Логическое имя файла справочника |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Программа showt.c | |
//------------------------------------------------- | |
//Выводит на экран все записи из файла tel_num.txt | |
//------------------------------------------------- | |
#include "my.h" | |
void Show(void) | |
{ | |
int i; | |
//Если файл невозможно открыть для чтения, то завершение работы программы | |
if ((F_tel = fopen(File, "r")) == NULL) | |
{ | |
fprintf(stderr, "\"%s\" : невозможно открыть\n",File); | |
exit(1); | |
} | |
//Чтение числа записей (Count) в файле | |
if(fread(&Count, sizeof(int), 1, F_tel) != 1) | |
{ | |
fprintf(stderr, "\"%s\" : ошибка чтения\n", File); | |
exit(1); | |
} | |
//В цикле осуществляется вывод всех записей | |
for (i=0; i < Count; i++) | |
{ | |
fread(Name, 1, MAX_NAME, F_tel); //Читается имя | |
fread(Number, 1, MAX_NUMBER, F_tel); //Читается номер | |
if (ferror(F_tel)) //Проверяется отсутствие ошибки | |
{ | |
fprintf(stderr, "\"%s\" : ошибка чтения\n'', File); | |
exit(1); | |
} | |
printf("Фамилия: %s; номер телефона: %s\n", Name, Number); | |
} | |
fclose(F_tel); | |
} | |
void main(void) | |
{ | |
Show( ); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Модуль subt.c | |
//------------------------------------------------------------ | |
//Функция Sub( ) удаляет заданную строку из файла tel_num.txt | |
//------------------------------------------------------------ | |
void Sub(char *str) | |
{ | |
int i, j; | |
char temp[MAX_NAME + MAX_NUMBER]; //Временный массив | |
if ((F_tel = fopen(File, "r+")) == NULL) | |
{ | |
fprintf(stderr, "\"%s\" : невозможно открыть\n", File); | |
exit(1); | |
} | |
if (fread(&Count, sizeof(int), 1, F_tel) != 1) | |
{ | |
fprintf(stderr, "\"%s\" : ошибка чтения\n", File); | |
exit(1); | |
} | |
//В цикле осуществляется поиск удаляемой строки в файле | |
for (i = 0; i < Count; i++) | |
{ | |
fread(temp, 1, MAX_NAME + MAX_NUMBER, F_tel); | |
if (ferror(F_tel)) | |
{ | |
fprintf(stderr, "\"%s\" : ошибка чтения\n", File); | |
exit(1); | |
} | |
if (strcmp(str, temp) == 0) //Если срока найдена | |
{ | |
for (j = i; j < Count; j++) //она удаляется | |
{ | |
fread(temp, 1, MAX_NAME + MAX_NUMBER, F_tel); | |
fseek(F_tel, (long)(j*(MAX_NAME+MAX_NUMBER)+2L), SEEK_SET); | |
fwrite(temp, 1, MAX_NAME + MAX_NUMBER, F_tel); | |
fseek(F_tel, (long)((j+2)*(MAX_NAME+MAX_NUMBER)+2L), SEEK_SET); | |
if (ferror(F_tel)) | |
{ | |
fprintf(stderr, "\"%s\" : ошибка чтения\n", File); | |
exit(1); | |
} | |
} | |
--Count; //При удалении строки декремент Count | |
fseek(F_tel, 0L, SEEK_SET); //Установка указателя | |
//Запись уменьшенного значения Count в файл | |
if (fwrite(&Count, sizeof(Count), 1, F_tel) != 1) | |
{ | |
fprintf(stderr, "\"%s\" : ошибка записи\n", File); | |
exit(1); | |
} | |
fclose(F_tel); | |
puts("Запись удалена из файла"); | |
return; | |
} | |
} | |
fprintf(stderr, "\"%s\" : отсутствует в базе данных\n", File); | |
fclose(F_tel); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment