init commit

This commit is contained in:
2025-04-13 21:48:15 +03:00
commit 23255e9121
192 changed files with 12200 additions and 0 deletions
+53
View File
@@ -0,0 +1,53 @@
#include <stdio.h>
#include <stdlib.h>
enum
{
NUM_OF_DIGITS = '9' - '0' + 1,
NUM_OF_LETTERS = 'z' - 'a' + 1,
BIT_MASK_1 = 0b111011,
BIT_MASK_2 = 0b001000,
MAX_NUM = 64,
};
int
main(void)
{
int c;
while ((c = getchar()) != EOF) {
int code = 0;
if (c <= '9' && c >= '0') {
code = c - '0' + 1;
} else if (c <= 'z' && c >= 'a') {
code = c - 'a' + NUM_OF_DIGITS + 1;
} else if (c <= 'Z' && c >= 'A') {
code = c - 'A' + NUM_OF_DIGITS + NUM_OF_LETTERS + 1;
}
if (code == 0) {
continue;
}
code = code & BIT_MASK_1;
code ^= BIT_MASK_2;
int res = 0;
if (code <= NUM_OF_DIGITS && code >= 1) {
res = code - 1 + '0';
} else if (code <= NUM_OF_DIGITS + NUM_OF_LETTERS && code >= NUM_OF_DIGITS + 1) {
res = code + 'a' - NUM_OF_DIGITS - 1;
} else if (code <= NUM_OF_DIGITS + NUM_OF_LETTERS * 2 && code >= NUM_OF_DIGITS + NUM_OF_LETTERS + 1) {
res = code + 'A' - NUM_OF_DIGITS - NUM_OF_LETTERS - 1;
} else if (code == 0) {
res = '@';
} else if (code == MAX_NUM - 1) {
res = '#';
}
putchar(res);
}
return 0;
}
+80
View File
@@ -0,0 +1,80 @@
#include <stdio.h>
#include <stdlib.h>
enum
{
MAX_N = 2000
};
int
is_prime(int num)
{
if (num <= 1) {
return 0;
}
if (num <= 3) {
return 1;
}
if (num % 2 == 0 || num % 3 == 0) {
return 0;
}
for (int i = 5; i * i <= num; i += 6) {
if (num % i == 0 || num % (i + 2) == 0) {
return 0;
}
}
return 1;
}
int
main(void)
{
int n;
if (scanf("%d", &n) != 1) {
fprintf(stderr, "Error reading input\n");
return 1;
}
if (n >= MAX_N || !is_prime(n)) {
return 1;
}
// двумерный под хранение результата. Не может быть одномерным, т.к. заполняются столбцы по порядку
int **mas = (int **) malloc(n * sizeof(mas));
if (mas == NULL) {
return 1;
}
for (int i = 0; i < n; i++) {
mas[i] = (int *) malloc(n * sizeof(*mas));
if (mas[i] == NULL) {
for (int j = 0; j < i; j++) {
free(mas[j]);
}
free(mas);
return 1;
}
}
for (int i = 1; i < n; i++) {
for (int a = 0; a < n; a++) {
mas[i][(a * i) % n] = a;
}
}
for (int j = 0; j < n; j++) {
for (int i = 1; i < n; i++) {
printf("%d ", mas[i][j]);
}
printf("\n");
}
for (int i = 0; i < n; i++) {
free(mas[i]);
}
free(mas);
return 0;
}
+78
View File
@@ -0,0 +1,78 @@
#include <stdio.h>
#include <stdlib.h>
void
swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
return;
}
int
next_permutation(int *arr, int n)
{
int i = n - 2;
while (i >= 0 && arr[i] >= arr[i + 1]) {
i--;
}
if (i < 0) {
return 0;
}
int j = n - 1;
while (arr[j] <= arr[i]) {
j--;
}
swap(&arr[i], &arr[j]);
int pt1 = i + 1, pt2 = n - 1;
while (pt1 < pt2) {
swap(&arr[pt1++], &arr[pt2--]);
}
return 1;
}
int
main()
{
int n;
if (scanf("%d", &n) != 1) {
fprintf(stderr, "Error reading input\n");
return 1;
}
if (n <= 0 || n >= 10) {
return 1;
}
int *arr = (int *) malloc(n * sizeof(*arr));
if (arr == NULL) {
return 1;
}
for (int i = 0; i < n; i++) {
arr[i] = i + 1;
}
do {
for (int i = 0; i < n; i++) {
printf("%d", arr[i]);
}
printf("\n");
} while (next_permutation(arr, n));
free(arr);
return 0;
}
+51
View File
@@ -0,0 +1,51 @@
#include <stdlib.h>
#include <malloc.h>
#include <stdio.h>
int
cmp(const void *a, const void *b)
{
if (*(int *) a % 2 == 0) {
if (*(int *) b % 2 == 1) {
return -1;
}
if (*(int *) a > *(int *) b) {
return 1;
}
if (*(int *) a < *(int *) b) {
return -1;
}
return 0;
}
if (*(int *) b % 2 == 0) {
return 1;
}
if (*(int *) a > *(int *) b) {
return -1;
}
if (*(int *) a < *(int *) b) {
return 1;
}
return 0;
}
void
sort_even_odd(size_t count, int *data)
{
qsort(data, count, sizeof(int), cmp);
}
int
main()
{
int a[] = {4, 2, 5, 3, 1, 0, -4, -2, -68, 23, 3};
sort_even_odd(sizeof(a) / sizeof(a[0]), a);
for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++) {
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
+3
View File
@@ -0,0 +1,3 @@
1) 'a'
2) 1
3) 7
+1129
View File
File diff suppressed because it is too large Load Diff
+133
View File
@@ -0,0 +1,133 @@
/*
Copyright (c) 2009 Dave Gamble
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef cJSON__h
#define cJSON__h
// #ifdef __cplusplus
// extern "C"
//{
// #endif
/* cJSON Types: */
#define cJSON_False 0
#define cJSON_True 1
#define cJSON_NULL 2
#define cJSON_Number 3
#define cJSON_String 4
#define cJSON_Array 5
#define cJSON_Object 6
#define cJSON_IsReference 256
/* The cJSON structure: */
typedef struct cJSON
{
struct cJSON *next, *prev; /* next/prev allow you to walk array/object chains. Alternatively, use
GetArraySize/GetArrayItem/GetObjectItem */
struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the
array/object. */
int type; /* The type of the item, as above. */
char *valuestring; /* The item's string, if type==cJSON_String */
int valueint; /* The item's number, if type==cJSON_Number */
double valuedouble; /* The item's number, if type==cJSON_Number */
char
*string; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
} cJSON;
typedef struct cJSON_Hooks
{
void *(*malloc_fn)(size_t sz);
void (*free_fn)(void *ptr);
} cJSON_Hooks;
/* Supply malloc, realloc and free functions to cJSON */
extern void cJSON_InitHooks(cJSON_Hooks *hooks);
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
extern cJSON *cJSON_Parse(const char *value);
/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */
extern char *cJSON_Print(cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
extern char *cJSON_PrintUnformatted(cJSON *item);
/* Delete a cJSON entity and all subentities. */
extern void cJSON_Delete(cJSON *c);
/* Returns the number of items in an array (or object). */
extern int cJSON_GetArraySize(cJSON *array);
/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
extern cJSON *cJSON_GetArrayItem(cJSON *array, int item);
/* Get item "string" from object. Case insensitive. */
extern cJSON *cJSON_GetObjectItem(cJSON *object, const char *string);
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back
* to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
extern const char *cJSON_GetErrorPtr();
/* These calls create a cJSON item of the appropriate type. */
extern cJSON *cJSON_CreateNull();
extern cJSON *cJSON_CreateTrue();
extern cJSON *cJSON_CreateFalse();
extern cJSON *cJSON_CreateBool(int b);
extern cJSON *cJSON_CreateNumber(double num);
extern cJSON *cJSON_CreateString(const char *string);
extern cJSON *cJSON_CreateArray();
extern cJSON *cJSON_CreateObject();
/* These utilities create an Array of count items. */
extern cJSON *cJSON_CreateIntArray(int *numbers, int count);
extern cJSON *cJSON_CreateFloatArray(float *numbers, int count);
extern cJSON *cJSON_CreateDoubleArray(double *numbers, int count);
extern cJSON *cJSON_CreateStringArray(const char **strings, int count);
/* Append item to the specified array/object. */
extern void cJSON_AddItemToArray(cJSON *array, cJSON *item);
extern void cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new
* cJSON, but don't want to corrupt your existing cJSON. */
extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
extern void cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
/* Remove/Detatch items from Arrays/Objects. */
extern cJSON *cJSON_DetachItemFromArray(cJSON *array, int which);
extern void cJSON_DeleteItemFromArray(cJSON *array, int which);
extern cJSON *cJSON_DetachItemFromObject(cJSON *object, const char *string);
extern void cJSON_DeleteItemFromObject(cJSON *object, const char *string);
/* Update array items. */
extern void cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
extern void cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem);
#define cJSON_AddNullToObject(object, name) cJSON_AddItemToObject(object, name, cJSON_CreateNull())
#define cJSON_AddTrueToObject(object, name) cJSON_AddItemToObject(object, name, cJSON_CreateTrue())
#define cJSON_AddFalseToObject(object, name) cJSON_AddItemToObject(object, name, cJSON_CreateFalse())
#define cJSON_AddNumberToObject(object, name, n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n))
#define cJSON_AddStringToObject(object, name, s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s))
// #ifdef __cplusplus
// }
// #endif
#endif
+12
View File
@@ -0,0 +1,12 @@
break parse_value
commands
silent
set $count = $count + 1
if $count == 2
print item->type
continue
end
continue
end
set $count = 0
run
+12
View File
@@ -0,0 +1,12 @@
break parse_string if $pc == *parse_string + <offset_to_line>
commands
silent
set $count = $count + 1
if $count == 4
print len
continue
end
continue
end
set $count = 0
run
Binary file not shown.
+4
View File
@@ -0,0 +1,4 @@
[ZoneTransfer]
ZoneId=3
ReferrerUrl=https://unicorn.ejudge.ru/ej/client/view-problem-submit/Sa889e21564f40a8b?prob_id=80
HostUrl=https://unicorn.ejudge.ru/ej/client?SID=a889e21564f40a8b&prob_id=80&action=194&file=gdb-1-task.tar
BIN
View File
Binary file not shown.
+27
View File
@@ -0,0 +1,27 @@
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
void
task1()
{
cJSON *item;
char *json = "{"
"\"a\" : true, "
"\"b\" : { "
"\"c\":\"stro\\\"ka\""
"}"
"}";
item = cJSON_Parse(json);
cJSON_Delete(item);
}
int
main(int argc, char **argv)
{
task1();
return 0;
}
+1126
View File
File diff suppressed because it is too large Load Diff
+133
View File
@@ -0,0 +1,133 @@
/*
Copyright (c) 2009 Dave Gamble
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef cJSON__h
#define cJSON__h
// #ifdef __cplusplus
// extern "C"
//{
// #endif
/* cJSON Types: */
#define cJSON_False 0
#define cJSON_True 1
#define cJSON_NULL 2
#define cJSON_Number 3
#define cJSON_String 4
#define cJSON_Array 5
#define cJSON_Object 6
#define cJSON_IsReference 256
/* The cJSON structure: */
typedef struct cJSON
{
struct cJSON *next, *prev; /* next/prev allow you to walk array/object chains. Alternatively, use
GetArraySize/GetArrayItem/GetObjectItem */
struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the
array/object. */
int type; /* The type of the item, as above. */
char *valuestring; /* The item's string, if type==cJSON_String */
int valueint; /* The item's number, if type==cJSON_Number */
double valuedouble; /* The item's number, if type==cJSON_Number */
char
*string; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
} cJSON;
typedef struct cJSON_Hooks
{
void *(*malloc_fn)(size_t sz);
void (*free_fn)(void *ptr);
} cJSON_Hooks;
/* Supply malloc, realloc and free functions to cJSON */
extern void cJSON_InitHooks(cJSON_Hooks *hooks);
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
extern cJSON *cJSON_Parse(const char *value);
/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */
extern char *cJSON_Print(cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
extern char *cJSON_PrintUnformatted(cJSON *item);
/* Delete a cJSON entity and all subentities. */
extern void cJSON_Delete(cJSON *c);
/* Returns the number of items in an array (or object). */
extern int cJSON_GetArraySize(cJSON *array);
/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
extern cJSON *cJSON_GetArrayItem(cJSON *array, int item);
/* Get item "string" from object. Case insensitive. */
extern cJSON *cJSON_GetObjectItem(cJSON *object, const char *string);
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back
* to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
extern const char *cJSON_GetErrorPtr();
/* These calls create a cJSON item of the appropriate type. */
extern cJSON *cJSON_CreateNull();
extern cJSON *cJSON_CreateTrue();
extern cJSON *cJSON_CreateFalse();
extern cJSON *cJSON_CreateBool(int b);
extern cJSON *cJSON_CreateNumber(double num);
extern cJSON *cJSON_CreateString(const char *string);
extern cJSON *cJSON_CreateArray();
extern cJSON *cJSON_CreateObject();
/* These utilities create an Array of count items. */
extern cJSON *cJSON_CreateIntArray(int *numbers, int count);
extern cJSON *cJSON_CreateFloatArray(float *numbers, int count);
extern cJSON *cJSON_CreateDoubleArray(double *numbers, int count);
extern cJSON *cJSON_CreateStringArray(const char **strings, int count);
/* Append item to the specified array/object. */
extern void cJSON_AddItemToArray(cJSON *array, cJSON *item);
extern void cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new
* cJSON, but don't want to corrupt your existing cJSON. */
extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
extern void cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
/* Remove/Detatch items from Arrays/Objects. */
extern cJSON *cJSON_DetachItemFromArray(cJSON *array, int which);
extern void cJSON_DeleteItemFromArray(cJSON *array, int which);
extern cJSON *cJSON_DetachItemFromObject(cJSON *object, const char *string);
extern void cJSON_DeleteItemFromObject(cJSON *object, const char *string);
/* Update array items. */
extern void cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
extern void cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem);
#define cJSON_AddNullToObject(object, name) cJSON_AddItemToObject(object, name, cJSON_CreateNull())
#define cJSON_AddTrueToObject(object, name) cJSON_AddItemToObject(object, name, cJSON_CreateTrue())
#define cJSON_AddFalseToObject(object, name) cJSON_AddItemToObject(object, name, cJSON_CreateFalse())
#define cJSON_AddNumberToObject(object, name, n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n))
#define cJSON_AddStringToObject(object, name, s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s))
// #ifdef __cplusplus
// }
// #endif
#endif
Binary file not shown.
+4
View File
@@ -0,0 +1,4 @@
[ZoneTransfer]
ZoneId=3
ReferrerUrl=https://unicorn.ejudge.ru/ej/client/view-problem-submit/Sa889e21564f40a8b?prob_id=81
HostUrl=https://unicorn.ejudge.ru/ej/client?SID=a889e21564f40a8b&prob_id=81&action=194&file=gdb-2-task.tar
BIN
View File
Binary file not shown.
+30
View File
@@ -0,0 +1,30 @@
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
void
task2()
{
cJSON *item;
char *text;
item = cJSON_Parse("{"
"\"name\" : \"Ivanov\","
"\"age\" : 25"
"}");
text = cJSON_PrintUnformatted(item);
puts(text);
free(text);
cJSON_Delete(item);
}
int
main(int argc, char **argv)
{
task2();
return 0;
}
+1
View File
@@ -0,0 +1 @@
{"name":"Ivanov","age":25}
+22
View File
@@ -0,0 +1,22 @@
#include <unistd.h>
#include <sys/types.h>
#include <wait.h>
#include <stdio.h>
int
proc(void)
{
int pid = fork();
if (!pid) {
write(1, "1\n", 2);
}
return pid;
}
int
main(int argc, char **argv)
{
proc(), proc(), proc();
return 0;
}
+1
View File
@@ -0,0 +1 @@
proc(), proc(), proc()
+35
View File
@@ -0,0 +1,35 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
#include <sys/types.h>
int
main()
{
pid_t pid;
pid = fork();
if (!pid) {
pid = fork();
if (!pid) {
printf("3 ");
return 0;
} else if (pid == -1) {
return 1;
} else {
wait(NULL);
printf("2 ");
}
return 0;
} else if (pid == -1) {
return 1;
} else {
wait(NULL);
printf("1");
}
printf("\n");
return 0;
}
+39
View File
@@ -0,0 +1,39 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
enum
{
MAX_LEN = 8
};
void
process_line(int line_number)
{
char buffer[MAX_LEN + 1] = {0};
read(0, buffer, sizeof(buffer) - 1);
long long number = strtoll(buffer, NULL, 10);
long long square = number * number;
printf("%d %lld\n", line_number, square);
return;
}
int
main()
{
pid_t pid;
for (int i = 0; i < 3; i++) {
if ((pid = fork()) == 0) {
process_line(i + 1);
exit(0);
}
}
while (wait(NULL) != -1)
;
return 0;
}
+1
View File
@@ -0,0 +1 @@
3
+38
View File
@@ -0,0 +1,38 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int
main()
{
pid_t pid;
int n;
if (scanf("%d", &n) != 1) {
return 1;
}
for (int i = 1; i <= n; i++) {
printf("%d", i);
fflush(stdout);
if (i == n) {
printf("\n");
return 0;
} else {
printf(" ");
fflush(stdout);
}
pid = fork();
if (!pid) {
continue;
} else {
wait(NULL);
return 0;
}
}
return 0;
}
+1
View File
@@ -0,0 +1 @@
1 2 3
+43
View File
@@ -0,0 +1,43 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
#include <sys/types.h>
int
main()
{
pid_t pid;
int n;
pid = fork();
if (!pid) {
for (;;) {
if (scanf("%d", &n) != 1) {
return 0;
}
pid = fork();
if (!pid) {
continue;
}
int status;
wait(&status);
if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status)) {
return -1;
}
printf("%d\n", n);
return 0;
}
} else {
int status;
wait(&status);
if (pid == -1 || !WIFEXITED(status) || WEXITSTATUS(status)) {
printf("-1\n");
}
}
return 0;
}
+47
View File
@@ -0,0 +1,47 @@
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
// CMD < FILE1 >> FILE2 2> FILE3
enum
{
EXIT_ERROR = 42,
ACCESS_FILE = 0660
};
int
main(int argc, char **argv)
{
char *cmd = argv[1];
char *file1 = argv[2];
char *file2 = argv[3];
char *file3 = argv[4];
pid_t pid = fork();
if (pid == 0) {
int fd1 = open(file1, O_RDONLY);
int fd2 = open(file2, O_WRONLY | O_APPEND | O_CREAT, ACCESS_FILE);
int fd3 = open(file3, O_WRONLY | O_TRUNC | O_CREAT, ACCESS_FILE);
if (fd1 == -1 || fd2 == -1 || fd3 == -1) {
_exit(EXIT_ERROR);
}
if (dup2(fd1, 0) == -1 || dup2(fd2, 1) == -1 || dup2(fd3, 2) == -1) {
_exit(EXIT_ERROR);
}
execlp(cmd, cmd, NULL);
_exit(EXIT_ERROR);
} else {
int status;
wait(&status);
printf("%d\n", status);
}
return 0;
}
+47
View File
@@ -0,0 +1,47 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int
run_command(char *cmd)
{
pid_t pid = fork();
if (pid == -1) {
perror("fork");
exit(1);
} else if (pid == 0) {
execlp(cmd, cmd, (char *) NULL);
perror("execlp");
exit(1);
} else {
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
return 1;
} else {
return 0;
}
}
}
int
main(int argc, char *argv[])
{
int cmd1_success = run_command(argv[1]);
int cmd2_success = 0;
if (!cmd1_success) {
cmd2_success = run_command(argv[2]);
}
if (cmd1_success || cmd2_success) {
if (run_command(argv[3])) {
exit(0);
} else {
exit(1);
}
}
exit(1);
}
+36
View File
@@ -0,0 +1,36 @@
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int
run(const char *cmd)
{
pid_t pid = fork();
if (pid == -1) {
exit(1);
} else if (pid == 0) {
execlp(cmd, cmd, NULL);
_exit(1);
}
int status;
waitpid(pid, &status, 0);
return WIFEXITED(status) && !WEXITSTATUS(status);
} // 1 - при успехе
int
main(int argc, char **argv)
{
if (argc != 4) {
return 1;
}
char *cmd1 = argv[1];
char *cmd2 = argv[2];
char *cmd3 = argv[3];
return !((run(cmd1) || run(cmd2)) && run(cmd3));
}
+59
View File
@@ -0,0 +1,59 @@
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
int
check(void)
{
int succes = 0;
int status;
while (wait(&status) != -1) {
if (WIFEXITED(status) && !WEXITSTATUS(status)) {
succes++;
}
}
return succes;
}
void
run(char *cmd)
{
pid_t pid = fork();
if (pid == -1) {
exit(1);
} else if (pid == 0) {
execlp(cmd, cmd, NULL);
_exit(1);
}
return;
} // 1 - при успехе
int
main(int argc, char **argv)
{
int succes = 0;
for (int i = 1; i < argc; ++i) {
if (argv[i][0] == 's') {
succes += check();
run(argv[i] + 1);
succes += check();
} else if (argv[i][0] == 'p') {
run(argv[i] + 1);
} else {
fprintf(stderr, "Error in arguments\n");
exit(1);
}
}
succes += check();
printf("%d\n", succes);
return 0;
}
+89
View File
@@ -0,0 +1,89 @@
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <linux/limits.h>
#include <time.h>
int
main(int argc, char **argv)
{
if (argc < 2) {
return 1;
}
char script_template[] = "#!/usr/bin/env python3\n"
"import os\n"
"print(";
char script_end[] = ")\n"
"os.remove(__file__)\n";
size_t script_size = strlen(script_template) + strlen(script_end) + 1;
for (int i = 1; i < argc; i++) {
script_size += strlen(argv[i]) + 1;
}
char *script_content;
if (!(script_content = malloc(script_size))) {
return 1;
}
strcpy(script_content, script_template);
for (int i = 1; i < argc; i++) {
strcat(script_content, argv[i]);
if (i < argc - 1) {
strcat(script_content, "*");
}
}
strcat(script_content, script_end);
char *tmpdir = getenv("XDG_RUNTIME_DIR");
if (!tmpdir) {
tmpdir = getenv("TMPDIR");
if (!tmpdir) {
tmpdir = "/tmp";
}
}
char script_path[PATH_MAX];
int r = snprintf(script_path, sizeof(script_path), "%s/%d", tmpdir, (int) (getpid() * time(NULL) % 1000000));
if (r < 0 || r > PATH_MAX) {
exit(1);
}
int fd = open(script_path, O_RDWR | O_CREAT | O_EXCL, 0600);
if (fd == -1) {
free(script_content);
return 1;
}
FILE *script_file = fdopen(fd, "w");
if (!script_file) {
close(fd);
unlink(script_path);
free(script_content);
return 1;
}
fprintf(script_file, "%s", script_content);
fclose(script_file);
free(script_content);
if (chmod(script_path, 0700) == -1) {
unlink(script_path);
return 1;
}
execl(script_path, script_path, (char *) NULL);
unlink(script_path);
return 1;
}
+74
View File
@@ -0,0 +1,74 @@
#include <stdio.h>
#include <unistd.h>
#include <wait.h>
#include <time.h>
#include <sys/types.h>
enum
{
YEAR_OFFSET = 1900
};
int
main(void)
{
int fd[2];
pipe(fd);
time_t delta;
struct tm *dt;
pid_t pid = fork();
if (pid == 0) {
pid = fork();
if (pid == 0) {
pid = fork();
if (pid == 0) {
close(fd[0]);
delta = time(NULL);
if (write(fd[1], &delta, sizeof(delta)) == -1 || write(fd[1], &delta, sizeof(delta)) == -1 ||
write(fd[1], &delta, sizeof(delta)) == -1) {
_exit(1);
}
} else if (pid == -1) {
_exit(1);
}
close(fd[1]);
wait(NULL);
if (read(fd[0], &delta, sizeof(delta)) == -1) {
_exit(1);
}
dt = localtime(&delta);
printf("D:%02d\n", dt->tm_mday);
fflush(stdout);
_exit(0);
} else if (pid == -1) {
_exit(1);
}
close(fd[1]);
wait(NULL);
if (read(fd[0], &delta, sizeof(delta)) == -1) {
_exit(1);
}
dt = localtime(&delta);
printf("M:%02d\n", dt->tm_mon + 1);
fflush(stdout);
_exit(0);
} else if (pid == -1) {
_exit(1);
}
close(fd[1]);
wait(NULL);
if (read(fd[0], &delta, sizeof(delta)) == -1) {
_exit(1);
}
dt = localtime(&delta);
printf("Y:%04d\n", dt->tm_year + YEAR_OFFSET);
fflush(stdout);
return 0;
}
+92
View File
@@ -0,0 +1,92 @@
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
enum
{
ACCESS_FILE = 0660
};
int
main(int argc, char **argv)
{
char *cmd1 = argv[1];
char *cmd2 = argv[2];
char *cmd3 = argv[3];
char *file1 = argv[4];
char *file2 = argv[5];
int fd1 = open(file1, O_RDONLY);
int fd2 = open(file2, O_WRONLY | O_APPEND | O_CREAT, ACCESS_FILE);
if (fd1 == -1 || fd2 == -1) {
exit(1);
}
int fd[2];
if (pipe(fd) == -1) {
return 1;
}
pid_t pid = fork();
if (pid == 0) {
close(fd[0]);
if (dup2(fd[1], 1) == -1) {
_exit(1);
}
pid = fork();
if (pid == 0) {
if (dup2(fd1, 0) == -1) {
_exit(1);
}
execlp(cmd1, cmd1, NULL);
_exit(1);
} else if (pid == -1) {
exit(1);
}
int status;
wait(&status);
if (WIFEXITED(status) && !WEXITSTATUS(status)) {
pid = fork();
if (pid == 0) {
execlp(cmd2, cmd2, NULL);
_exit(1);
} else if (pid == -1) {
exit(1);
}
wait(NULL);
}
_exit(0);
} else if (pid == -1) {
exit(1);
}
close(fd[1]);
pid = fork();
if (pid == 0) {
if (dup2(fd2, 1) == -1 || dup2(fd[0], 0)) {
_exit(1);
}
execlp(cmd3, cmd3, NULL);
_exit(1);
} else if (pid == -1) {
exit(1);
}
close(fd[0]);
while (wait(NULL) != -1)
;
return 0;
}
+71
View File
@@ -0,0 +1,71 @@
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
void
ex(void)
{
// разослать SIGKILL
// а некому.
exit(1);
}
void
swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
return;
}
int
main(int argc, char **argv)
{
int fd1[2];
int fd2[2];
if (close(2) == -1 || pipe(fd1) == -1 || pipe(fd2)) {
ex();
}
for (int i = 1; i < argc; ++i) {
pid_t pid = fork();
if (pid == 0) {
if (i != 1 && i != argc - 1) {
if (dup2(fd2[1], 1) == -1 || dup2(fd1[0], 0) == -1) {
ex();
}
} else if (i == 1) {
if (dup2(fd2[1], 1) == -1) {
ex();
}
} else {
if (dup2(fd1[0], 0) == -1) {
ex();
}
}
close(fd1[0]);
close(fd1[1]);
close(fd2[0]);
close(fd2[1]);
execlp(argv[i], argv[i], NULL);
_exit(1);
} else if (pid == -1) {
ex();
}
swap(&fd1[0], &fd2[0]);
swap(&fd1[1], &fd2[1]);
wait(NULL);
}
return 0;
}
+73
View File
@@ -0,0 +1,73 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <wait.h>
int
main(int argc, char **argv)
{
int n = (int) strtoll(argv[1], NULL, 10);
int fd1[2];
int fd2[2];
pipe(fd1);
pipe(fd2);
int tmp = 1;
write(fd2[1], &tmp, sizeof(tmp));
if (!fork()) {
int i = 0;
close(fd1[0]);
close(fd2[1]);
while (i < n) {
if (read(fd2[0], &i, sizeof(i)) == -1) {
return 0;
}
if (i >= n) {
write(fd1[1], &i, sizeof(i));
break;
}
printf("%d %d\n", 1, i);
fflush(stdout);
i++;
write(fd1[1], &i, sizeof(i));
}
return 0;
} else if (!fork()) {
int i = 0;
close(fd2[0]);
close(fd1[1]);
while (i < n) {
if (read(fd1[0], &i, sizeof(i)) == -1) {
return 0;
}
if (i >= n) {
write(fd1[1], &i, sizeof(i));
break;
}
printf("%d %d\n", 2, i);
fflush(stdout);
i++;
write(fd2[1], &i, sizeof(i));
}
return 0;
}
close(fd1[0]);
close(fd1[1]);
close(fd2[0]);
close(fd2[1]);
while (wait(NULL) != -1)
;
printf("Done\n");
return 0;
}
+35
View File
@@ -0,0 +1,35 @@
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <signal.h>
volatile int cnt = 0;
void
f(int n)
{
if (cnt == 5) {
exit(0);
}
printf("%d\n", cnt++);
fflush(stdout);
return;
}
int
main(int argc, char *argv[])
{
sigaction(SIGHUP, &(struct sigaction){.sa_handler = f, .sa_flags = SA_RESTART}, NULL);
printf("%d\n", getpid());
fflush(stdout);
for (;;) {
pause();
}
return 0;
}
+51
View File
@@ -0,0 +1,51 @@
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <signal.h>
volatile int mode = 0; // 0 - + 1 - *
void
mul(int n)
{
mode = 1;
return;
}
void
sum(int n)
{
mode = 0;
return;
}
int
main(int argc, char *argv[])
{
sigaction(SIGINT, &(struct sigaction){.sa_handler = sum, .sa_flags = SA_RESTART}, NULL);
sigaction(SIGQUIT, &(struct sigaction){.sa_handler = mul, .sa_flags = SA_RESTART}, NULL);
printf("%d\n", getpid());
fflush(stdout);
int res = 0, tmp;
while (scanf("%d", &tmp) == 1) {
if (mode == 0) {
__builtin_add_overflow(res, tmp, &res);
} else {
__builtin_mul_overflow(res, tmp, &res);
}
printf("%d\n", res);
fflush(stdout);
}
// for (;;) {
// pause();
// }
return 0;
}
+68
View File
@@ -0,0 +1,68 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <wait.h>
int
main(int argc, char **argv)
{
int n = (int) strtoll(argv[1], NULL, 10);
int fd[2];
pipe(fd);
int tmp = 1;
write(fd2[1], &tmp, sizeof(tmp));
if (!fork()) {
int i = 0;
close(fd[0]);
while (i < n) {
if (read(fd2[0], &i, sizeof(i)) == -1) {
return 0;
}
if (i >= n) {
write(fd1[1], &i, sizeof(i));
break;
}
printf("%d %d\n", 1, i);
fflush(stdout);
i++;
write(fd1[1], &i, sizeof(i));
}
return 0;
} else if (!fork()) {
int i = 0;
close(fd2[0]);
close(fd1[1]);
while (i < n) {
if (read(fd1[0], &i, sizeof(i)) == -1) {
return 0;
}
if (i >= n) {
write(fd1[1], &i, sizeof(i));
break;
}
printf("%d %d\n", 2, i);
fflush(stdout);
i++;
write(fd2[1], &i, sizeof(i));
}
return 0;
}
close(fd[0]);
close(fd[1]);
while (wait(NULL) != -1)
;
printf("Done\n");
return 0;
}
+75
View File
@@ -0,0 +1,75 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/wait.h>
volatile sig_atomic_t sigusr1_received = 0;
void
sigusr1_handler(int signum)
{
sigusr1_received = 1;
}
int
main(int argc, char **argv)
{
int n = (int) strtol(argv[1], NULL, 10);
int fd[2];
pipe(fd);
signal(SIGUSR1, sigusr1_handler);
if (!fork()) {
close(fd[0]);
FILE *out = fdopen(fd[1], "w");
int i = 1;
while (i <= n) {
printf("1 %d\n", i);
fflush(stdout);
fprintf(out, "%d\n", i);
fflush(out);
kill(getppid(), SIGUSR1);
pause();
if (i >= n) {
break;
}
i++;
}
fclose(out);
return 0;
} else if (!fork()) {
close(fd[1]);
FILE *in = fdopen(fd[0], "r");
int i;
while (1) {
if (i >= n) {
break;
}
i++;
printf("2 %d\n", i);
fflush(stdout);
kill(getppid(), SIGUSR1);
pause();
}
fclose(in);
return 0;
}
close(fd[0]);
close(fd[1]);
while (wait(NULL) != -1)
;
printf("Done\n");
return 0;
}
+72
View File
@@ -0,0 +1,72 @@
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <signal.h>
volatile int last_prime = 0;
volatile int cnt = 0;
void
f(int n)
{
if (++cnt == 4) {
exit(0);
}
printf("%d\n", last_prime);
fflush(stdout);
return;
}
void
exit_term(int n)
{
exit(0);
return;
}
int
is_prime(int n)
{
if (n < 2) {
return 0;
}
for (int i = 2; i * i <= n; ++i) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int
main(int argc, char *argv[])
{
sigaction(SIGINT, &(struct sigaction){.sa_handler = f, .sa_flags = SA_RESTART}, NULL);
sigaction(SIGTERM, &(struct sigaction){.sa_handler = exit_term, .sa_flags = SA_RESTART}, NULL);
printf("%d\n", getpid());
fflush(stdout);
int a, b;
scanf("%d", &a);
scanf("%d", &b);
a = (a < 2) ? 2 : a;
for (int i = a; i < b; ++i) {
if (is_prime(i)) {
last_prime = i;
}
}
printf("-1\n");
fflush(stdout);
return 0;
}
+34
View File
@@ -0,0 +1,34 @@
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
volatile int count = 0;
void
func(int sign)
{
if (count < 5) {
printf("%d\n", count);
fflush(stdout);
count++;
} else {
exit(0);
}
}
int
main(int argc, char *argv[])
{
printf("%d\n", getpid());
fflush(stdout);
if (signal(SIGHUP, func) == SIG_ERR) {
exit(1);
}
for (;;) {
pause();
}
return 0;
}
+27
View File
@@ -0,0 +1,27 @@
// #include <stdio.h>
typedef int STYPE;
typedef unsigned int UTYPE;
STYPE
bit_reverse(STYPE value)
{
UTYPE result = 0;
UTYPE uvalue = (UTYPE) value;
for (int i = 0; i < sizeof(STYPE) * 8; i++) {
result <<= 1;
result |= uvalue & 1;
uvalue >>= 1;
}
return (STYPE) result;
}
// int main(void) {
// STYPE value = 0b10101010;
// STYPE result = bit_reverse(value);
// printf("%d\n", result);
// printf("%ld\n", sizeof(STYPE));
// return 0;
// }
+41
View File
@@ -0,0 +1,41 @@
#include <stdio.h>
#include <stdint.h>
#include <errno.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
long long res_pos = 0, res_neg = 0;
for (int i = 1; i < argc; i++) {
char *p;
errno = 0;
long long val = strtol(argv[i], &p, 10);
if (*p || errno || (int32_t) val != val || argv[i] == p) {
return 1;
}
// int32_t tmp;
if (val >= 0) {
// if (!__builtin_add_overflow(res_pos, val, &tmp)) {
res_pos += val;
// }
} else {
// if (!__builtin_add_overflow(res_neg, val, &tmp)) {
res_neg += val;
// }
}
}
// if (!(res_neg && res_pos)) {
// printf("0\n");
// } else {
// printf("%d\n", res_pos);
// printf("%d\n", res_neg);
// }
printf("%lld\n", res_pos);
printf("%lld\n", res_neg);
return 0;
}
+39
View File
@@ -0,0 +1,39 @@
#include <stdio.h>
#include <stdint.h>
#include <errno.h>
#include <stdlib.h>
#include <math.h>
enum
{
PRCN = 10000,
};
int
main(int argc, char *argv[])
{
long double a = 0;
for (int i = 1; i < argc; i++) {
char *p;
errno = 0;
long double val = strtod(argv[i], &p);
if (*p || errno || argv[i] == p) {
return 1;
}
if (i == 1) {
a = val * PRCN;
} else {
a = round(a * (100.L + val) / 100.L);
}
}
if (argc == 1) {
return 1;
}
printf("%.4Lf\n", a / PRCN);
return 0;
}
+22
View File
@@ -0,0 +1,22 @@
#include <stdio.h>
enum
{
MY_INT_MAX = ~0u >> (!0),
MY_INT_MIN = ~(~0u >> (!0))
};
int
satsum(int v1, int v2)
{
int sum;
if (!__builtin_add_overflow(v1, v2, &sum)) {
return sum;
} else if (v1 > 0) {
return MY_INT_MAX;
} else {
return MY_INT_MIN;
}
return 0;
}
+19
View File
@@ -0,0 +1,19 @@
enum
{
MY_INT_MAX = ~0u >> (!0),
MY_INT_MIN = ~(~0u >> (!0))
};
int
satsum(int v1, int v2)
{
if (v1 > 0 && (signed int) MY_INT_MAX - v1 < v2) {
return MY_INT_MAX;
}
if (v1 < 0 && (signed int) MY_INT_MIN - v1 > v2) {
return MY_INT_MIN;
}
return v1 + v2;
}
+45
View File
@@ -0,0 +1,45 @@
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
enum
{
CHAR_IN_INT = 12
};
struct Elem
{
struct Elem *next;
char *str;
};
struct Elem *
dup_elem(struct Elem *head)
{
if (head == NULL) {
return NULL;
}
head->next = dup_elem(head->next);
errno = 0;
char *p;
long n = strtol(head->str, &p, 10);
if (errno || (int) n != n || n == INT_MAX || *p || p == head->str) {
return head;
}
struct Elem *new = calloc(1, sizeof(*new));
if (new == NULL) {
exit(1);
}
char *str = calloc(CHAR_IN_INT, sizeof(*str));
snprintf(str, CHAR_IN_INT, "%d", (int) n + 1);
new->str = str;
new->next = head;
return new;
}
+59
View File
@@ -0,0 +1,59 @@
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <limits.h>
#include <errno.h>
#include <stdlib.h>
enum
{
PEN_CHAR_BIT = 12
};
int
safe_write(int fd, void *buf, size_t count)
{
errno = 0;
size_t bytes_written = 0;
while (bytes_written < count) {
ssize_t res = write(fd, buf + bytes_written, count - bytes_written);
if (res < 0) {
if (errno == EINTR) {
errno = 0;
continue;
}
fprintf(stderr, "Error writing to file descriptor %d\n", fd);
close(fd);
exit(1); // TODO: по-хорошему заменить на внешний обработчик ошибок
}
bytes_written += res;
}
return bytes_written;
}
int
main(int argc, char **argv)
{
int fdout = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0600);
if (fdout == -1) {
return 1;
}
unsigned char res[4];
unsigned tmp;
while (scanf("%u", &tmp) == 1) {
res[0] = (tmp & (0x0F << (CHAR_BIT + PEN_CHAR_BIT))) >> (CHAR_BIT + PEN_CHAR_BIT);
res[1] = (tmp & (0xFF << PEN_CHAR_BIT)) >> PEN_CHAR_BIT;
res[2] = (tmp & (0x0F << CHAR_BIT)) >> CHAR_BIT;
res[3] = tmp & 0xFF;
safe_write(fdout, res, sizeof(res));
}
close(fdout);
return 0;
}
+91
View File
@@ -0,0 +1,91 @@
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
void
str_to_ll(char *str, long long *num)
{
errno = 0;
char *endptr;
*num = strtoll(str, &endptr, 10);
if (*endptr || errno || endptr == str) {
fprintf(stderr, "Invalid number: %s\n", str);
exit(1); // TODO: по-хорошему заменить на внешний обработчик ошибок
}
return;
}
int
safe_write(int fd, void *buf, size_t count)
{
errno = 0;
size_t bytes_written = 0;
while (bytes_written < count) {
ssize_t res = write(fd, buf + bytes_written, count - bytes_written);
if (res < 0) {
if (errno == EINTR) {
errno = 0;
continue;
}
fprintf(stderr, "Error writing to file descriptor %d\n", fd);
close(fd);
exit(1); // TODO: по-хорошему заменить на внешний обработчик ошибок
}
bytes_written += res;
}
return bytes_written;
}
int
main(int argc, char **argv)
{
if (argc < 3) {
return 1;
}
long long n;
str_to_ll(argv[2], &n);
int fd = open(argv[1], O_RDWR);
if (fd == -1) {
return 1;
}
int is_first = 1;
double prev;
for (int i = 0; i < n; ++i) {
double tmp;
int r = read(fd, &tmp, sizeof(tmp));
if (r == -1 || (r && r != sizeof(tmp))) {
return 1;
}
if (r < 1) {
break;
}
if (!is_first) {
tmp -= prev;
} else {
is_first = 0;
}
if (lseek(fd, -sizeof(tmp), SEEK_CUR) == -1) {
return 1;
}
safe_write(fd, &tmp, sizeof(tmp));
prev = tmp;
}
close(fd);
return 0;
}
+93
View File
@@ -0,0 +1,93 @@
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <limits.h>
#include <errno.h>
ssize_t
my_write(int fd, void *buf, size_t count)
{
size_t count_1 = 0;
ssize_t count_2;
while (count_1 != count) {
count_2 = write(fd, buf, count - count_1);
if (count_2 == -1) {
return -1;
} else if (count_2 == 0) {
return (ssize_t) count_1;
} else {
count_1 += (size_t) count_2;
}
}
return (ssize_t) count_1;
}
ssize_t
my_read(int fd, void *buf, size_t count)
{
size_t count_1 = 0;
ssize_t count_2;
while (count_1 != count) {
count_2 = read(fd, buf, count - count_1);
if (count_2 == -1) {
return -1;
} else if (count_2 == 0) {
return (ssize_t) count_1;
} else {
count_1 += (size_t) count_2;
}
}
return (ssize_t) count_1;
}
int
main(int argc, char **argv)
{
if (argc < 2) {
return 1;
}
int fd;
if ((fd = open(argv[1], O_RDWR)) == -1) {
return 1;
}
long long num, min, shift = 0;
if (my_read(fd, &min, sizeof(min)) < sizeof(min)) {
if (errno) {
close(fd);
return 1;
}
close(fd);
return 0;
}
for (int i = (int) sizeof(num); my_read(fd, &num, sizeof(min)) == sizeof(min); i += (int) sizeof(num)) {
if (num < min) {
min = num;
shift = i;
}
}
lseek(fd, shift, 0);
if (errno) {
close(fd);
return 1;
}
if (min != LLONG_MIN) {
min = -min;
}
if (my_write(fd, &min, sizeof(min)) != sizeof(min)) {
close(fd);
return 1;
}
close(fd);
if (errno) {
return 1;
}
}
+118
View File
@@ -0,0 +1,118 @@
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <limits.h>
#include <errno.h>
enum
{
ARGS_NUM = 2,
};
int
safe_read(int fd, void *buf, size_t count)
{
errno = 0;
size_t bytes_read = 0;
while (bytes_read < count) {
ssize_t res = read(fd, buf + bytes_read, count - bytes_read);
if (res < 0) {
if (errno == EINTR) {
errno = 0;
continue;
}
fprintf(stderr, "Error reading from file descriptor %d\n", fd);
close(fd);
exit(1); // TODO: по-хорошему заменить на внешний обработчик ошибок
}
if (res == 0) {
break;
}
bytes_read += res;
}
return bytes_read;
}
int
safe_write(int fd, void *buf, size_t count)
{
errno = 0;
size_t bytes_written = 0;
while (bytes_written < count) {
ssize_t res = write(fd, buf + bytes_written, count - bytes_written);
if (res < 0) {
if (errno == EINTR) {
errno = 0;
continue;
}
fprintf(stderr, "Error writing to file descriptor %d\n", fd);
close(fd);
exit(1); // TODO: по-хорошему заменить на внешний обработчик ошибок
}
bytes_written += res;
}
return bytes_written;
}
int
main(int argc, char *argv[])
{
if (argc != ARGS_NUM) {
fprintf(stderr, "Wrong number of arguments\n");
return 1;
}
int fd = open(argv[1], O_RDWR);
if (fd == -1) {
fprintf(stderr, "Error opening file %s\n", argv[1]);
return 1;
}
long long num, min_num = LLONG_MAX;
off_t pt_min = -1;
while (safe_read(fd, &num, sizeof(num)) == sizeof(num)) {
if (num < min_num || pt_min == -1) {
min_num = num;
if ((pt_min = lseek(fd, 0, SEEK_CUR) - sizeof(num)) == -1) {
fprintf(stderr, "Error in navigate file %s\n", argv[1]);
return 1;
}
}
}
if (min_num != LLONG_MIN && pt_min != -1) {
min_num = -min_num;
if (lseek(fd, pt_min, SEEK_SET) == -1) {
fprintf(stderr, "Error in navigate file %s\n", argv[1]);
return 1;
}
if (safe_write(fd, &min_num, sizeof(min_num)) != sizeof(num)) {
printf("Error while writing");
return 1;
}
}
close(fd);
return 0;
}
+98
View File
@@ -0,0 +1,98 @@
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <limits.h>
#include <stdint.h>
struct Node
{
int32_t key;
int32_t left_idx;
int32_t right_idx;
};
void
read_struct(int fd, struct Node *node, int is_le)
{
unsigned char buf[sizeof(*node)];
int n = 0;
while (n != sizeof(*node)) {
ssize_t off = read(fd, buf + n, sizeof(*node) - n);
if (off == -1) {
close(fd);
exit(1);
}
n += off;
}
// int r = read(fd, buf, sizeof(*node));
// if (r == -1) {
// close(fd);
// exit(1);
// }
int n_byte = sizeof(int32_t);
node->key = 0;
node->left_idx = 0;
node->right_idx = 0;
for (int j = 0; j < n_byte; ++j) {
int off = (is_le) ? (CHAR_BIT * (sizeof(uint32_t) - (j + 1))) : (CHAR_BIT * j);
node->key |= (uint32_t) buf[j] << off;
node->left_idx |= (uint32_t) buf[j + n_byte * 1] << off;
node->right_idx |= (uint32_t) buf[j + n_byte * 2] << off;
}
}
void
inorder_traversal(int fd, int32_t idx, int is_le)
{
if (idx == 0) {
return;
}
if (idx == -1) {
idx = 0;
}
struct Node tmp;
if (lseek(fd, idx * sizeof(struct Node), SEEK_SET) == -1) {
close(fd);
exit(1);
}
read_struct(fd, &tmp, is_le);
inorder_traversal(fd, tmp.right_idx, is_le);
printf("%d\n", tmp.key);
inorder_traversal(fd, tmp.left_idx, is_le);
return;
}
int
main(int argc, char **argv)
{
if (argc != 2) {
return 1;
}
int test = 1;
int is_le = 0;
if (*(char *) &test == 1) {
is_le = 1;
}
int fd = open(argv[1], O_RDONLY);
if (fd == -1) {
return 1;
}
inorder_traversal(fd, -1, is_le);
putchar('\n');
close(fd);
return 0;
}
+102
View File
@@ -0,0 +1,102 @@
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
typedef struct Node
{
int32_t key;
int32_t left_idx;
int32_t right_idx;
} Node;
int
convert_num_to_sys(char num[])
{
unsigned res = 0;
for (int i = 0; i < sizeof(res); ++i) {
unsigned cur = (unsigned char) num[sizeof(res) - i - 1];
res ^= (cur << (CHAR_BIT * i));
}
return (int) res;
}
int
read_int(int fd)
{
int res = 0;
char buf[sizeof(res)];
int pos = 0;
while (pos != sizeof(res)) {
ssize_t off = read(fd, buf + pos, sizeof(res) - pos);
if (off == -1) {
printf("Error, can't read from file\n");
exit(1);
}
pos += off;
}
res = convert_num_to_sys(buf);
return res;
}
Node
read_node(int fd)
{
Node new_node;
new_node.key = read_int(fd);
new_node.right_idx = read_int(fd);
new_node.left_idx = read_int(fd);
return new_node;
}
void
dfs(Node head, int fd)
{
if (head.left_idx != 0) {
if (lseek(fd, head.left_idx * sizeof(Node), SEEK_SET) == -1) {
printf("Error? can't seek throw file\n");
exit(1);
}
Node left_node = read_node(fd);
dfs(left_node, fd);
}
printf("%d\n", head.key);
if (head.right_idx != 0) {
if (lseek(fd, head.right_idx * sizeof(Node), SEEK_SET) == -1) {
printf("Error? can't seek throw file\n");
exit(1);
}
Node right_node = read_node(fd);
dfs(right_node, fd);
}
}
int
main(int argc, char *argv[])
{
if (argc < 2) {
printf("Error: Not enough argumens\n");
exit(1);
}
int fd = open(argv[1], O_RDONLY, 0600);
if (fd < 0) {
printf("Error: Can't open file\n");
exit(1);
}
struct stat st;
if (stat(argv[1], &st) == -1) {
printf("Error, can't get info about file\n");
exit(1);
}
if (st.st_size == 0) {
return 0;
}
Node head = read_node(fd);
dfs(head, fd);
close(fd);
}
+104
View File
@@ -0,0 +1,104 @@
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <limits.h>
struct Node
{
int32_t key;
int32_t left_idx;
int32_t right_idx;
};
void
inorder_traversal(struct Node *mas, int32_t idx, int32_t *keys, int32_t *pos)
{
if (idx == 0) {
return;
}
if (idx == -1) {
idx = 0;
}
inorder_traversal(mas, mas[idx].left_idx, keys, pos);
keys[(*pos)++] = mas[idx].key;
inorder_traversal(mas, mas[idx].right_idx, keys, pos);
return;
}
int
main(int argc, char **argv)
{
if (argc < 2) {
return 1;
}
int test = 1;
int is_le = 0;
if (*(char *) &test == 1) {
is_le = 1;
}
int fd = open(argv[1], O_RDONLY);
if (fd == -1) {
return 1;
}
int n = lseek(fd, 0, SEEK_END) / sizeof(struct Node);
lseek(fd, 0, SEEK_SET);
struct Node *mas = calloc(n, sizeof(struct Node));
for (int i = 0; i < n; ++i) {
struct Node tmp;
unsigned char buf[sizeof(tmp)];
int r = read(fd, buf, sizeof(tmp));
if (r == -1) {
free(mas);
close(fd);
return 1;
}
if (r < 12) {
break;
}
int n_byte = sizeof(int32_t);
tmp.key = 0;
tmp.left_idx = 0;
tmp.right_idx = 0;
if (is_le) {
for (int j = 0; j < n_byte; ++j) {
tmp.key |= (u_int32_t) buf[j] << (CHAR_BIT * j);
tmp.left_idx |= (u_int32_t) buf[j + n_byte * 1] << (CHAR_BIT * j);
tmp.right_idx |= (u_int32_t) buf[j + n_byte * 2] << (CHAR_BIT * j);
}
} else {
for (int j = 0; j < n_byte; ++j) {
tmp.key |= (u_int32_t) buf[j] << (CHAR_BIT * (sizeof(u_int32_t) - (j + 1)));
tmp.left_idx |= (u_int32_t) buf[j + n_byte * 1] << (CHAR_BIT * (sizeof(u_int32_t) - (j + 1)));
tmp.right_idx |= (u_int32_t) buf[j + n_byte * 2] << (CHAR_BIT * (sizeof(u_int32_t) - (j + 1)));
}
}
mas[i] = tmp;
}
int32_t *keys = calloc(n, sizeof(int32_t));
int32_t pos = 0;
inorder_traversal(mas, -1, keys, &pos);
for (int32_t i = 0; i < pos; ++i) {
printf("%d\n", keys[i]);
}
free(keys);
free(mas);
close(fd);
return 0;
}
+78
View File
@@ -0,0 +1,78 @@
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <limits.h>
struct Node
{
int32_t key, left_idx, right_idx;
};
void
inorder_traversal(struct Node *mas, int32_t idx, int32_t *keys, int32_t *pos)
{
if (idx == 0) {
return;
}
if (idx == -1) {
idx = 0;
}
inorder_traversal(mas, mas[idx].left_idx, keys, pos), keys[(*pos)++] = mas[idx].key,
inorder_traversal(mas, mas[idx].right_idx, keys, pos);
return;
}
int
main(int argc, char **argv)
{
if (argc < 2) {
return 1;
}
int test = 1, is_le = 0;
if (*(char *) &test == 1) {
is_le = 1;
}
int fd = open(argv[1], O_RDONLY);
if (fd == -1) {
return 1;
}
int n = lseek(fd, 0, SEEK_END) / sizeof(struct Node);
lseek(fd, 0, SEEK_SET);
struct Node *mas = calloc(n, sizeof(struct Node));
for (int i = 0; i < n; ++i) {
struct Node tmp;
unsigned char buf[sizeof(tmp)];
int r = read(fd, buf, sizeof(tmp));
if (r == -1) {
free(mas), close(fd);
return 1;
}
if (r < 12) {
break;
}
int n_byte = sizeof(int32_t);
tmp.key = 0, tmp.left_idx = 0, tmp.right_idx = 0;
if (is_le) {
for (int j = 0; j < n_byte; ++j) {
tmp.key |= (u_int32_t) buf[j] << (CHAR_BIT * j),
tmp.left_idx |= (u_int32_t) buf[j + n_byte * 1] << (CHAR_BIT * j),
tmp.right_idx |= (u_int32_t) buf[j + n_byte * 2] << (CHAR_BIT * j);
}
} else {
for (int j = 0; j < n_byte; ++j) {
tmp.key |= (u_int32_t) buf[j] << (CHAR_BIT * (sizeof(u_int32_t) - (j + 1))),
tmp.left_idx |= (u_int32_t) buf[j + n_byte * 1] << (CHAR_BIT * (sizeof(u_int32_t) - (j + 1))),
tmp.right_idx |= (u_int32_t) buf[j + n_byte * 2] << (CHAR_BIT * (sizeof(u_int32_t) - (j + 1)));
}
}
mas[i] = tmp;
}
int32_t *keys = calloc(n, sizeof(int32_t)), pos = 0;
inorder_traversal(mas, -1, keys, &pos);
for (int32_t i = 0; i < pos; ++i) {
printf("%d\n", keys[i]);
}
free(keys), free(mas), close(fd);
return 0;
}
+68
View File
@@ -0,0 +1,68 @@
#include <stdio.h>
#include <stdlib.h>
#include <sys/file.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <limits.h>
#include <endian.h>
int
main(int argc, char *argv[])
{
if (argc != 4) {
return 1;
}
int fdin = open(argv[1], O_RDONLY);
int fdout = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (fdin == -1 || fdout == -1) {
return 1;
}
char *p;
errno = 0;
long long mod = strtoll(argv[3], &p, 10);
if (errno || *p || p == argv[3] || !mod || (int32_t) mod != mod) {
return 1;
}
unsigned long long res = 0;
unsigned long long num = 1;
unsigned char buf;
int r = read(fdin, &buf, sizeof(buf));
if (r && r != sizeof(buf)) {
return 1;
}
while (r > 0) {
for (int i = 0; i < CHAR_BIT; i++) {
num %= mod;
res += (num * num) % mod;
res %= mod;
if (buf & (1 << i)) {
int32_t res32 = res;
if (write(fdout, &res32, sizeof(res32)) == -1) {
return 1;
}
}
num++;
}
r = read(fdin, &buf, sizeof(buf));
if (r && r != sizeof(buf)) {
return 1;
}
}
if (r == -1) {
return 1;
}
close(fdin);
close(fdout);
return 0;
}
+72
View File
@@ -0,0 +1,72 @@
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <assert.h>
struct Node
{
int32_t key;
int32_t left_idx;
int32_t right_idx;
};
void
create_binary_file(const char *filename, struct Node *nodes, int n)
{
int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
for (int i = 0; i < n; ++i) {
struct Node node = nodes[i];
node.key = htonl(node.key);
node.left_idx = htonl(node.left_idx);
node.right_idx = htonl(node.right_idx);
write(fd, &node, sizeof(struct Node));
}
close(fd);
}
char *
execute_program(const char *filename)
{
char command[256];
snprintf(command, sizeof(command), "./04 %s", filename);
FILE *fp = popen(command, "r");
if (fp == NULL) {
perror("popen");
exit(EXIT_FAILURE);
}
char *output = malloc(1024);
fread(output, 1, 1024, fp);
pclose(fp);
return output;
}
void
test_case(struct Node *nodes, int n, const char *expected_output)
{
const char *filename = "test.bin";
create_binary_file(filename, nodes, n);
char *output = execute_program(filename);
assert(strcmp(output, expected_output) == 0);
free(output);
}
int
main()
{
struct Node nodes1[] = {{10, 1, 2}, {5, 0, 0}, {15, 0, 0}};
test_case(nodes1, 3, "15 10 5 \n");
struct Node nodes2[] = {{20, 1, 2}, {10, 0, 0}, {30, 0, 0}};
test_case(nodes2, 3, "30 20 10 \n");
printf("All tests passed.\n");
return 0;
}
+32
View File
@@ -0,0 +1,32 @@
import struct
# Define the Node structure
class Node:
def __init__(self, key, left_idx, right_idx):
self.key = key
self.left_idx = left_idx
self.right_idx = right_idx
# Create a binary search tree
nodes = [
Node(20, 1, 2), # Root node
Node(-10, 3, 4), # Left child of root
Node(30, 5, 6), # Right child of root
Node(-5, 0, 0), # Left child of node with key 10
Node(15, 0, 0), # Right child of node with key 10
Node(25, 0, 0), # Left child of node with key 30
Node(35, 0, 0) # Right child of node with key 30
]
# Write the nodes to a binary file in Big-Endian format
with open('test_tree.bin', 'wb') as f:
for node in nodes:
# Pack the data in Big-Endian format
f.write(struct.pack('>i', node.key))
f.write(struct.pack('>i', node.left_idx))
f.write(struct.pack('>i', node.right_idx))
# Verify the content of the file
with open('test_tree.bin', 'rb') as f:
content = f.read()
print("Binary content:", bytes(content).hex())
+31
View File
@@ -0,0 +1,31 @@
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/types.h>
#include <string.h>
enum
{
KIBIBYTE = 1024
};
int
main(int argc, char *argv[])
{
long long int sum = 0;
for (int i = 1; i < argc; ++i) {
struct stat st;
if (!(lstat(argv[i], &st) < 0 || st.st_nlink != 1 || !S_ISREG(st.st_mode) || st.st_size % KIBIBYTE != 0)) {
sum += st.st_size;
}
}
printf("%lld\n", sum);
return 0;
}
+32
View File
@@ -0,0 +1,32 @@
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
enum
{
MAX_MODE = 0777,
};
int
main(int argc, char *argv[])
{
const char s[] = "rwxrwxrwx";
for (int i = 1; i < argc; ++i) {
char *p;
errno = 0;
int n = strtol(argv[i], &p, 8);
if (errno || *p || p == argv[i] || n > MAX_MODE || n < 0) {
return 1;
}
for (int j = 0; j < sizeof(s) - 1; ++j) {
putchar((n & (1 << (sizeof(s) - 2 - j))) ? s[j] : '-');
}
printf("\n");
}
return 0;
}
+36
View File
@@ -0,0 +1,36 @@
#include <stdlib.h>
enum
{
RWX_PERMISSIONS = 0777,
};
int
parse_rwx_permissions(const char *str)
{
if (str == NULL) {
return -1;
}
const char expected[] = "rwxrwxrwx";
unsigned res = 0;
int i = 0;
while (str[i]) {
res <<= 1;
if (str[i] == expected[i] && expected[i]) {
res |= 1;
} else if (str[i] != '-' || !expected[i]) {
return -1;
}
++i;
}
if (res > RWX_PERMISSIONS || res < 0 || expected[i]) {
return -1;
}
return res;
}
+92
View File
@@ -0,0 +1,92 @@
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/types.h>
#include <string.h>
#include <linux/limits.h>
struct File
{
char *pathname;
__ino_t st_ino;
__dev_t st_dev;
};
int
cmp_structs(struct File elem1, struct stat elem2)
{
return elem1.st_dev == elem2.st_dev && elem1.st_ino == elem2.st_ino;
}
int
cmp_mas(const void *a, const void *b)
{
struct File elem1 = *(struct File *) a;
struct File elem2 = *(struct File *) b;
return strcmp(elem1.pathname, elem2.pathname);
}
int
main(int argc, char **argv)
{
struct File *mas = calloc(10, sizeof(struct File));
if (mas == NULL) {
fprintf(stderr, "Error! Can't calloc mas\n");
return 1;
}
int n = 0, capacity = 10;
for (int i = 1; i < argc; ++i) {
struct stat st;
if (stat(argv[i], &st) < 0) {
continue;
}
int flag = 0;
for (int j = 0; j < n; ++j) {
if (cmp_structs(mas[j], st)) { // 1 if equal
flag = 1;
if (strcmp(mas[j].pathname, argv[i]) < 0) {
mas[j].pathname = argv[i];
}
break;
}
}
if (!flag) {
if (n == capacity) {
capacity *= 2;
while (!realloc(mas, capacity * sizeof(mas[0])) && capacity > n) {
capacity--;
}
if (capacity == n) {
fprintf(stderr, "Error! Can't realloc mas\n");
return 1;
}
}
mas[n++] = (struct File){argv[i], st.st_ino, st.st_dev};
}
}
qsort(mas, n, sizeof(mas[0]), cmp_mas);
for (int i = 0; i < n; ++i) {
printf("%s\n", mas[i].pathname);
}
free(mas);
return 0;
}
+99
View File
@@ -0,0 +1,99 @@
#include <stdlib.h>
#include <string.h>
#include <linux/limits.h>
#include <stdio.h>
char *
relativize_path(const char *path1, const char *path2)
{
char *spath1 = calloc(strlen(path1) + 2, sizeof(char));
strcpy(spath1, path1);
spath1[strlen(path1)] = '\0';
if (spath1[strlen(path1) - 1] != '/') {
strcat(spath1, "/");
}
char *res;
if ((res = calloc(PATH_MAX, sizeof(char))) == NULL) {
exit(1);
}
int i = 0;
int ptr = 0;
while (spath1[i] == path2[i] && spath1[i]) {
if (spath1[i] == '/') {
ptr = i;
}
i++;
}
int deep1 = 0;
while (spath1[i]) {
if (spath1[i] == '/') {
deep1++;
}
i++;
}
if (!deep1 && path2[strlen(path2) - 1] == '/') {
snprintf(res, PATH_MAX, ".");
return res;
}
int deep2 = 0;
i = ptr + 1;
while (path2[i]) {
if (path2[i] == '/') {
deep2++;
}
i++;
}
for (int j = 0; j < deep1; j++) {
res[j * 3] = '.';
res[j * 3 + 1] = '.';
res[j * 3 + 2] = '/';
}
if (deep2 == 0 && deep1) {
if (res[strlen(res) - 1] == '/') {
res[strlen(res) - 1] = '\0';
}
return res;
}
snprintf(res + deep1 * 3, PATH_MAX - deep1 * 3, "%s", path2 + ptr + 1);
if (res[strlen(res) - 1] == '/') {
res[strlen(res) - 1] = '\0';
}
return res;
}
int
main()
{
const char *path1 = "/home/krosh/cmc/contest5";
const char *path2 = "/home/krosh/cmc/contest5/subdir/file.txt";
char *relative_path = relativize_path(path1, path2);
printf("Relative path: %s\n", relative_path);
const char *path3 = "/a/b/c/d";
const char *path4 = "/a/e/f";
printf("Relative path: %s\n", relativize_path(path3, path4));
const char *path5 = "/a/f/g/h/j";
const char *path6 = "/a/f/g/h";
printf("Relative path: %s\n", relativize_path(path5, path6));
const char *path7 = "/a";
const char *path8 = "/a";
printf("Relative path: %s\n", relativize_path(path7, path8));
return 0;
}
+99
View File
@@ -0,0 +1,99 @@
#include <stdlib.h>
#include <string.h>
#include <linux/limits.h>
#include <stdio.h>
char *
relativize_path(const char *path1, const char *path2)
{
char *spath1 = calloc(strlen(path1) + 2, sizeof(char));
strcpy(spath1, path1);
spath1[strlen(path1)] = '\0';
if (spath1[strlen(path1) - 1] != '/') {
strcat(spath1, "/");
}
char *res;
if ((res = calloc(PATH_MAX, sizeof(char))) == NULL) {
exit(1);
}
int i = 0;
int ptr = 0;
while (spath1[i] == path2[i] && spath1[i]) {
if (spath1[i] == '/') {
ptr = i;
}
i++;
}
int deep1 = 0;
while (spath1[i]) {
if (spath1[i] == '/') {
deep1++;
}
i++;
}
if (!deep1 && path2[strlen(path2) - 1] == '/') {
snprintf(res, PATH_MAX, ".");
return res;
}
int deep2 = 0;
i = ptr + 1;
while (path2[i]) {
if (path2[i] == '/') {
deep2++;
}
i++;
}
for (int j = 0; j < deep1; j++) {
res[j * 3] = '.';
res[j * 3 + 1] = '.';
res[j * 3 + 2] = '/';
}
if (deep2 == 0 && deep1) {
if (res[strlen(res) - 1] == '/') {
res[strlen(res) - 1] = '\0';
}
return res;
}
snprintf(res + deep1 * 3, PATH_MAX - deep1 * 3, "%s", path2 + ptr + 1);
if (res[strlen(res) - 1] == '/') {
res[strlen(res) - 1] = '\0';
}
return res;
}
int
main()
{
const char *path1 = "/home/krosh/cmc/contest5";
const char *path2 = "/home/krosh/cmc/contest5/subdir/file.txt";
char *relative_path = relativize_path(path1, path2);
printf("Relative path: %s\n", relative_path);
const char *path3 = "/a/b/c/d";
const char *path4 = "/a/e/f";
printf("Relative path: %s\n", relativize_path(path3, path4));
const char *path5 = "/a/f/g/h/j";
const char *path6 = "/a/f/g/h";
printf("Relative path: %s\n", relativize_path(path5, path6));
const char *path7 = "/a";
const char *path8 = "/a";
printf("Relative path: %s\n", relativize_path(path7, path8));
return 0;
}
+55
View File
@@ -0,0 +1,55 @@
#include <stdio.h> // Standard I/O functions
#include <stdlib.h> // Standard library functions: memory allocation, process control, conversions, etc.
#include <unistd.h> // POSIX API: read, write, close, etc.
#include <sys/types.h> // Data types used in system calls
#include <sys/stat.h> // Data returned by the functions fstat(), lstat(), and stat()
#include <limits.h> // Sizes of basic types
#include <dirent.h> // Directory entry format
#include <string.h> // String handling functions
enum
{
ARGS_NUM = 2,
};
int
main(int argc, char *argv[])
{
if (argc != ARGS_NUM) {
fprintf(stderr, "Wrong number of arguments\n");
return 1;
}
int n = 0;
DIR *ddir = opendir(argv[1]);
struct dirent *de;
while ((de = readdir(ddir))) {
char *name = calloc(PATH_MAX, sizeof(char));
if (!name) {
return 1;
}
int ret = snprintf(name, PATH_MAX, "%s/%s", argv[1], de->d_name);
if (ret < 0 || ret >= PATH_MAX) {
free(name);
return 1;
}
struct stat st;
if (stat(name, &st) < 0) {
continue;
}
char ext[] = ".exe";
if (S_ISREG(st.st_mode) && !access(name, X_OK) && strlen(name) >= 4 &&
!strcmp(name + strlen(name) - (sizeof(ext) - 1), ext)) {
++n;
}
}
printf("%d\n", n);
closedir(ddir);
return 0;
}
+68
View File
@@ -0,0 +1,68 @@
long long
stlen(char *buf)
{
long long i = 0;
for (; buf[i] != '\0'; ++i) {
}
return i;
}
long long
shift(char *buf, long long st, long long sh, long long len)
{
long long i = st;
if (i + sh > len) {
return len;
}
for (; i + sh <= len; ++i) {
buf[i] = buf[i + sh];
}
return len - sh;
}
void
normalize_path(char *buf)
{
long long len = stlen(buf);
for (int i = 1; buf[i]; ++i) {
if (buf[i] == '.' && buf[i - 1] == '/') {
if (buf[i + 1] == '.' && (buf[i + 2] == '/' buf[i + 2] == '\0')) {
if (i - 2 >= 0) {
int j;
for (j = i - 2; buf[j] != '/'; --j) {
}
++j;
if (buf[i + 2] == '/') {
len = shift(buf, j, i + 3 - j, len);
i = j - 1;
} else if (!buf[i + 2]) {
len = shift(buf, j, i + 2 - j, len);
i = j - 1;
}
} else {
if (buf[i + 2] == '/') {
len = shift(buf, i, 3, len);
--i;
} else if (!buf[i + 2]) {
len = shift(buf, i, 2, len);
--i;
}
}
} else if (buf[i + 1] == '/' buf[i + 1] == '\0') {
if (buf[i + 1] == '/') {
len = shift(buf, i, 2, len);
--i;
} else if (!buf[i + 1]) {
len = shift(buf, i, 1, len);
--i;
}
}
}
}
len = stlen(buf);
if (len != 1) {
if (buf[len - 1] == '/') {
buf[len - 1] = '\0';
}
}
}
+110
View File
@@ -0,0 +1,110 @@
#include <stdio.h> // Standard I/O functions
#include <stdlib.h> // Standard library functions: memory allocation, process control, conversions, etc.
#include <fcntl.h> // File control options
#include <unistd.h> // POSIX API: read, write, close, etc.
#include <sys/file.h> // File control options
#include <sys/types.h> // Data types used in system calls
#include <sys/stat.h> // Data returned by the functions fstat(), lstat(), and stat()
#include <linux/limits.h> // Sizes of basic types
#include <limits.h> // Sizes of basic types
#include <errno.h> // Error reporting macros
#include <stdint.h> // Exact-width integer types
#include <math.h> // Mathematical functions
#include <dirent.h> // Directory entry format
#include <string.h> // String handling functions
#include <sys/stat.h> // Data returned by the functions fstat(), lstat(), and stat()
// переписать на strcmp.
void
normalize_path(char *buf)
{
unsigned long long pt_real = 0, pt_res = 0;
unsigned long long len = 0; // проверить правильное вычисление длины
while (buf[len++] != '\0')
;
len--;
while (pt_real < len) {
printf("pt: %lld -- %d %d %d\n", pt_real, pt_real - 2 == len, buf[pt_real] == '.',
buf[pt_real + 1] == '.'); // может вызвать выход за массив
if ((len - pt_real >= 3 && buf[pt_real] == '.' && buf[pt_real + 1] == '.' && buf[pt_real + 2] == '/') ||
(pt_real - 2 == len && buf[pt_real] == '.' && buf[pt_real + 1] == '.')) {
printf("meow\n");
if (pt_real > 0 && buf[pt_real - 1] == '/') {
pt_real += 3;
if (pt_res == 1) {
continue;
}
if (pt_res == 0) { // impossible ?
pt_res = 1;
continue;
}
pt_res -= 2;
while (pt_res > 0 && buf[pt_res] != '/') {
pt_res--;
}
pt_res++;
continue;
}
} else if ((len - pt_real >= 2 && buf[pt_real] == '.' && buf[pt_real + 1] == '/') ||
(len == pt_real - 1 && buf[pt_real] == '.')) {
if (pt_real > 0 && buf[pt_real - 1] == '/') {
// printf("paw\n");
pt_real += 2;
continue;
}
}
buf[pt_res] = buf[pt_real];
pt_real++;
pt_res++;
}
// if (pt_real > 1 && buf[pt_real - 1] == '.') {
// if (pt_real > 2 && buf[pt_real - 2] == '.' && buf[pt_real - 3] == '/') {
// if (pt_res > 1) {
// pt_res -= 2;
// while (pt_res > 0 && buf[pt_res - 1] != '/') {
// pt_res--;
// }
// }
// } else if (pt_real > 1 && buf[pt_real - 2] == '/') {
// if (pt_res > 0) {
// pt_res--;
// }
// }
// }
buf[pt_res] = '\0';
if (pt_res > 1 && buf[pt_res - 1] == '/') {
buf[pt_res - 1] = '\0';
}
return;
}
int
main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "Usage: %s <path>\n", argv[0]);
return EXIT_FAILURE;
}
char path[PATH_MAX];
strncpy(path, argv[1], PATH_MAX - 1);
path[PATH_MAX - 1] = '\0';
normalize_path(path);
printf("Normalized path: %s\n", path);
return EXIT_SUCCESS;
}
+114
View File
@@ -0,0 +1,114 @@
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <linux/limits.h>
#include <limits.h>
#include <errno.h>
#include <stdint.h>
#include <math.h>
#include <dirent.h>
#include <string.h>
size_t
len(const char *buf)
{
size_t i = 0;
while (buf[i] != '\0') {
++i;
}
return i;
}
size_t
shift_left(char *str, size_t st, size_t shift_amount, size_t length)
{
size_t i = st;
if (i + shift_amount > length) {
return length;
}
while (i + shift_amount < length) {
str[i] = str[i + shift_amount];
++i;
}
return length - shift_amount;
}
void
normalize_path(char *path)
{
size_t length = len(path);
size_t i = 1;
while (path[i]) {
if (path[i - 1] == '/' && path[i] == '.') {
if (path[i + 1] == '.' && (path[i + 2] == '/' || !path[i + 2])) {
if (i < 1) {
if (path[i + 2] == '/') {
length = shift_left(path, i, 3, length);
--i;
} else if (!path[i + 2]) {
length = shift_left(path, i, 2, length);
--i;
}
} else {
size_t j = i - 2;
while (j > 0 && path[j] != '/') {
--j;
}
++j;
if (path[i + 2] == '/') {
length = shift_left(path, j, i + 3 - j, length);
i = j - 1;
} else if (!path[i + 2]) {
length = shift_left(path, j, i + 2 - j, length);
i = j - 1;
}
}
} else if (path[i + 1] == '/' || !path[i + 1]) {
if (path[i + 1] == '/') {
length = shift_left(path, i, 2, length);
--i;
} else if (!path[i + 1]) {
length = shift_left(path, i, 1, length);
--i;
}
}
}
++i;
}
if (len(path) != 1 && path[len(path) - 1] == '/') {
path[len(path) - 1] = '\0';
}
return;
}
int
main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "Usage: %s <path>\n", argv[0]);
return EXIT_FAILURE;
}
char path[PATH_MAX];
strncpy(path, argv[1], PATH_MAX - 1);
path[PATH_MAX - 1] = '\0';
normalize_path(path);
printf("Normalized path: %s\n", path);
return EXIT_SUCCESS;
}
+36
View File
@@ -0,0 +1,36 @@
#include <stdlib.h>
struct s1
{
char f1;
long long f2;
char f3;
};
struct s2
{
char f1;
char f3;
long long f2;
};
size_t
compactify(void *ptr, size_t size)
{
if (size == 0) {
return 0;
}
size_t count = size / sizeof(struct s1);
struct s1 *src = (struct s1 *) ptr;
struct s2 *dst = (struct s2 *) ptr;
for (size_t i = 0; i < count; ++i) {
struct s1 tmp = src[i];
dst[i].f1 = tmp.f1;
dst[i].f3 = tmp.f3;
dst[i].f2 = tmp.f2;
}
return count * sizeof(struct s2);
}
+119
View File
@@ -0,0 +1,119 @@
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <linux/limits.h>
#include <errno.h>
enum
{
ARGS_NUM = 3,
MAX_DIRS = 1000,
};
void
str_to_ll(char *str, long long *num)
{
errno = 0;
char *endptr;
*num = strtoll(str, &endptr, 10);
if (*endptr || errno || endptr == str) {
fprintf(stderr, "Invalid number: %s\n", str);
exit(1); // TODO: по-хорошему заменить на внешний обработчик ошибок
}
return;
}
void
list_files(char *path_from, const int start, size_t max_size, int depth)
{
if (depth > 4) {
return;
}
DIR *dir = opendir(path_from);
if (dir == NULL) {
return;
}
char **dirs = (char **) calloc(MAX_DIRS, sizeof(char *));
if (dirs == NULL) {
exit(1);
}
int cnt = 0;
struct dirent *dd;
while ((dd = readdir(dir))) {
if (!(strcmp(dd->d_name, ".") && strcmp(dd->d_name, ".."))) {
continue;
}
char name[PATH_MAX];
int ret = snprintf(name, sizeof(name), "%s/%s", path_from, dd->d_name);
if (ret < 0 || ret >= PATH_MAX) {
exit(1);
}
struct stat st;
if (lstat(name, &st) < 0) {
continue;
}
if (S_ISDIR(st.st_mode)) {
dirs[cnt] = (char *) calloc(PATH_MAX, sizeof(char));
memcpy(dirs[cnt], name, strlen(name));
cnt++;
} else if (st.st_size <= max_size && !access(name, R_OK) && S_ISREG(st.st_mode)) {
ret = snprintf(name, sizeof(name), "%s/%s", path_from + start + 1, dd->d_name);
if (ret < 0 || ret >= PATH_MAX) {
exit(1);
}
printf("%s\n", name + (name[0] == '/'));
}
}
for (int i = 0; i < cnt; i++) {
list_files(dirs[i], start, max_size, depth + 1);
free(dirs[i]);
}
closedir(dir);
free(dirs);
return;
}
int
main(int argc, char *argv[])
{
if (argc != ARGS_NUM) {
return 1;
}
int len_arg = strlen(argv[1]);
char *dir_path = calloc(PATH_MAX, sizeof(char));
memcpy(dir_path, argv[1], len_arg - (argv[1][len_arg - 1] == '/'));
int len_path = strlen(dir_path);
if (!len_path) {
dir_path[0] = '/';
dir_path[1] = '\0';
}
long long max_size;
str_to_ll(argv[2], &max_size);
list_files(dir_path, len_path, max_size, 1);
free(dir_path);
return EXIT_SUCCESS;
}
+56
View File
@@ -0,0 +1,56 @@
#include <stdio.h>
#include <stdlib.h>
#include <linux/limits.h>
#include <stdint.h>
#include <string.h>
int
main(int argc, char *argv[])
{
const char const_str[] = "18446744073709551616";
char tmp_str[PATH_MAX];
while (scanf("%s", tmp_str) == 1) {
int64_t res = 0;
uint64_t base = 1;
int is_overflow = 0;
for (int i = strlen(tmp_str) - 1; i >= 0; i--) {
char ch = tmp_str[i];
if (ch == 'a') {
if (__builtin_sub_overflow(res, base, &res)) {
is_overflow = 1;
break;
}
} else if (ch == '1') {
if (__builtin_add_overflow(res, base, &res)) {
is_overflow = 1;
break;
}
} else if (ch != '0') {
fprintf(stderr, "Invalid input\n");
return 1;
}
if (__builtin_mul_overflow(base, 3, &base) && i != 0) {
is_overflow = 1;
break;
}
}
if (is_overflow) {
printf("%s\n", const_str);
} else {
printf("%lld\n", res);
}
}
return 0;
}
+98
View File
@@ -0,0 +1,98 @@
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum
{
MAX_SYM_THREE_LEN = 64,
SYS_BASE = 3,
};
const char ERROR_OUTPUT[] = "18446744073709551616";
int
main(void)
{
int cur_num = getchar();
while (cur_num != EOF && isspace(cur_num)) {
cur_num = getchar();
}
long long res = 0;
bool overflow = false;
bool printed = false;
bool read = false;
while (cur_num != EOF) {
char cur_ch = cur_num;
if (isspace(cur_num)) {
if (!printed) {
if (overflow) {
printf("%s\n", ERROR_OUTPUT);
} else {
printf("%lld\n", res);
}
res = 0;
overflow = false;
printed = true;
}
} else {
read = true;
printed = false;
if (cur_ch == '1') {
long long temp = 0;
if (res < 0) {
if (__builtin_mul_overflow(res + 1, 3, &temp)) {
overflow = true;
}
if (__builtin_add_overflow(temp, 1, &res)) {
overflow = true;
}
if (__builtin_sub_overflow(res, 3, &temp)) {
overflow = true;
}
res = temp;
} else {
if (__builtin_mul_overflow(res, 3, &temp)) {
overflow = true;
}
if (__builtin_add_overflow(temp, 1, &res)) {
overflow = true;
}
}
} else if (cur_ch == 'a') {
long long temp = 0;
if (res > 0) {
if (__builtin_mul_overflow(res - 1, 3, &temp)) {
overflow = true;
}
if (__builtin_sub_overflow(temp, 1, &res)) {
overflow = true;
}
if (__builtin_add_overflow(res, 3, &temp)) {
overflow = true;
}
res = temp;
} else {
if (__builtin_mul_overflow(res, 3, &temp)) {
overflow = true;
}
if (__builtin_sub_overflow(temp, 1, &res)) {
overflow = true;
}
}
} else if (cur_ch == '0') {
long long temp = 0;
if (__builtin_mul_overflow(res, 3, &temp)) {
overflow = true;
}
res = temp;
}
}
cur_num = getchar();
}
if (cur_num == EOF && !printed && !overflow && read) {
printf("%lld\n", res);
}
}
+90
View File
@@ -0,0 +1,90 @@
#include <stdio.h>
#include <stdlib.h>
#include <linux/limits.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
int
main(int argc, char *argv[])
{
const char const_str[] = "18446744073709551616";
int ch, index = 0;
int64_t res = 0;
int is_overflow = 0;
while ((ch = getchar()) != EOF) {
if (!isspace(ch)) {
index = 1;
int64_t tmp = 0;
if (ch == 'a') {
if (res > 0) {
if (__builtin_mul_overflow(res - 1, 3, &tmp)) {
is_overflow = 1;
}
if (__builtin_sub_overflow(tmp, 1, &res)) {
is_overflow = 1;
}
if (__builtin_add_overflow(res, 3, &tmp)) {
is_overflow = 1;
}
res = tmp;
} else {
if (__builtin_mul_overflow(res, 3, &tmp)) {
is_overflow = 1;
}
if (__builtin_sub_overflow(tmp, 1, &res)) {
is_overflow = 1;
}
}
} else if (ch == '1') {
if (res > 0) {
if (__builtin_mul_overflow(res, 3, &tmp)) {
is_overflow = 1;
}
if (__builtin_add_overflow(tmp, 1, &res)) {
is_overflow = 1;
}
} else {
if (__builtin_mul_overflow(res + 1, 3, &tmp)) {
is_overflow = 1;
}
if (__builtin_add_overflow(tmp, 1, &res)) {
is_overflow = 1;
}
if (__builtin_sub_overflow(res, 3, &tmp)) {
is_overflow = 1;
}
res = tmp;
}
} else if (ch == '0') {
if (__builtin_mul_overflow(res, 3, &res)) {
is_overflow = 1;
}
}
} else {
if (index) {
if (is_overflow) {
printf("%s\n", const_str);
} else {
printf("%lld\n", res);
}
index = 0;
res = 0;
is_overflow = 0;
}
}
}
if (index) {
if (is_overflow) {
printf("%s\n", const_str);
} else {
printf("%lld\n", res);
}
}
return 0;
}
+54
View File
@@ -0,0 +1,54 @@
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
enum
{
THURSDAY = 4,
YEAR_OFFSET = 1900,
LAST_DIGIT_REM = 3,
GOOD_THURSDAY1 = 2,
GOOD_THURSDAY2 = 4
};
int
main(int argc, char *argv[])
{
int year;
if (scanf("%d", &year) != 1) {
fprintf(stderr, "Invalid input\n");
return 1;
}
struct tm t = {0};
t.tm_isdst = -1;
t.tm_mday = 1;
t.tm_year = year - YEAR_OFFSET;
int num_of_thursdays = 0, last_month = 0;
while (t.tm_year == year - YEAR_OFFSET) {
mktime(&t);
if (t.tm_mon != last_month) {
last_month = t.tm_mon;
num_of_thursdays = 0;
}
if (t.tm_wday == THURSDAY) {
num_of_thursdays++;
if (t.tm_mday % LAST_DIGIT_REM != 0 &&
(num_of_thursdays == GOOD_THURSDAY1 || num_of_thursdays == GOOD_THURSDAY2)) {
printf("%d %d\n", t.tm_mon + 1, t.tm_mday);
}
t.tm_mday += 7;
} else {
t.tm_mday++;
}
}
return 0;
}
+67
View File
@@ -0,0 +1,67 @@
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <errno.h>
#include <linux/limits.h>
void
check_and_sum_files(const char *dir1, const char *dir2, off_t *total_size)
{
DIR *d1 = opendir(dir1);
if (!d1) {
return;
}
struct dirent *entry;
while ((entry = readdir(d1)) != NULL) {
char path1[PATH_MAX];
int r = snprintf(path1, sizeof(path1), "%s/%s", dir1, entry->d_name);
if (r < 0 || r >= sizeof(path1)) {
_exit(1);
}
struct stat st1;
if (lstat(path1, &st1) == -1 || !S_ISREG(st1.st_mode)) {
continue;
}
if (access(path1, W_OK) == 0) {
char path2[PATH_MAX];
r = snprintf(path2, sizeof(path2), "%s/%s", dir2, entry->d_name);
if (r < 0 || r >= sizeof(path2)) {
_exit(1);
}
struct stat st2;
if (stat(path2, &st2) == -1) {
continue;
}
if (S_ISREG(st2.st_mode) && st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino) {
*total_size += st1.st_size;
}
}
}
closedir(d1);
}
int
main(int argc, char *argv[])
{
if (argc != 3) {
fprintf(stderr, "Usage: %s <directory1> <directory2>\n", argv[0]);
return 1;
}
off_t total_size = 0;
check_and_sum_files(argv[1], argv[2], &total_size);
printf("%ld\n", total_size);
return 0;
}
View File
+104
View File
@@ -0,0 +1,104 @@
#include <stdio.h>
#include <time.h>
enum
{
SYNODIC_PERIOD_DAYS = 29,
SYNODIC_PERIOD_HOURS = 12,
SYNODIC_PERIOD_MINUTES = 44,
FULL_MOON_YEAR = 2021,
FULL_MOON_MONTH = 5,
FULL_MOON_DAY = 26,
FULL_MOON_HOUR = 11,
FULL_MOON_MINUTE = 14,
};
void
add_synodic_period(struct tm *tm)
{
tm->tm_mday += SYNODIC_PERIOD_DAYS;
tm->tm_hour += SYNODIC_PERIOD_HOURS;
tm->tm_min += SYNODIC_PERIOD_MINUTES;
timegm(tm);
}
void
sub_synodic_period(struct tm *tm)
{
tm->tm_mday -= SYNODIC_PERIOD_DAYS;
tm->tm_hour -= SYNODIC_PERIOD_HOURS;
tm->tm_min -= SYNODIC_PERIOD_MINUTES;
timegm(tm);
}
struct tm
find_full_moon_after(struct tm start)
{
struct tm full_moon = {0};
full_moon.tm_isdst = -1;
full_moon.tm_year = FULL_MOON_YEAR - 1900;
full_moon.tm_mon = FULL_MOON_MONTH - 1;
full_moon.tm_mday = FULL_MOON_DAY;
full_moon.tm_hour = FULL_MOON_HOUR;
full_moon.tm_min = FULL_MOON_MINUTE;
timegm(&full_moon);
while (timegm(&full_moon) < timegm(&start)) {
add_synodic_period(&full_moon);
}
while (timegm(&full_moon) > timegm(&start)) {
sub_synodic_period(&full_moon);
}
add_synodic_period(&full_moon);
return full_moon;
}
struct tm
find_fourth_monday_after(struct tm start)
{
struct tm date = start;
date.tm_mday++;
int num_of_mondays = 0;
while (num_of_mondays < 4) {
timegm(&date);
if (date.tm_wday == 1) {
num_of_mondays++;
}
date.tm_mday++;
}
date.tm_mday--;
timegm(&date);
return date;
}
int
main()
{
int year;
if (scanf("%d", &year) != 1) {
return 1;
}
struct tm start = {0};
start.tm_isdst = -1;
start.tm_year = year - 1900;
start.tm_mday = 257;
timegm(&start);
struct tm full_moon = find_full_moon_after(start);
struct tm event_date = find_fourth_monday_after(full_moon);
printf("%04d-%02d-%02d\n", event_date.tm_year + 1900, event_date.tm_mon + 1, event_date.tm_mday);
return 0;
}
+20
View File
@@ -0,0 +1,20 @@
a a1 10a
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
a1
0
0
00 0
1a1a1110011100a101aa11a01010a0a011a0a10a1
1a1a1110011100a101aa11a01010a0a011a0a100a
a1a1aaa00aaa001a0a11aa10a0a01010aa101a001
a1a1aaa00aaa001a0a11aa10a0a01010aa101a00a
a1a1aaa00aaa001a0a11aa10a0a01010aa101a01a
1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
1 1
1
1
+32
View File
@@ -0,0 +1,32 @@
В ОЗУ 16-разрядного компьютера используется контроль целостности данных по
четности. Описать возможную структуру ячейки памяти и ее побитовое содержимое
для случая хранения в машинном слове восьмеричного числа 17735.
64 6
128 7
256 8
2 pow 10 = 1024
2 pow 11 = 2048
2 pow 12 = 4096
2 pow 13 = 8192
2 pow 14 = 16384
17735 -
16384 =
01351 -
01024 =
00327 -
00256 =
00071 -
00064 =
00007
0010 0010 1010 0111
xor all = 1 - somewhere
всё сверху хуйня, число восьмиричное
001 111 111 011 101
xor = 1
+9
View File
@@ -0,0 +1,9 @@
Пусть дано восьмеричное число 173357, являющееся адресом оперативной памяти,
расслоенной по 16 банкам. Банку с каким номером принадлежит заданный адрес?
001 111 011 011 101 111
1111 0110 1110 1111
4 bit
15?
+21
View File
@@ -0,0 +1,21 @@
#include <unistd.h>
typedef struct segment
{
unsigned int base;
unsigned int size;
} segment;
// 8-ми сегментная
unsigned int
VirtIntoPhys(segment *segTable, unsigned int VirtAdr)
{
unsigned int SegNum = VirtAdr >> 29;
unsigned int offset = (VirtAdr << 3) >> 3;
if (offset > segTable[SegNum].size) {
_exit(25);
}
return segTable[SegNum].base + offset;
}
+55
View File
@@ -0,0 +1,55 @@
#include <unistd.h>
#include <fcntl.h>
// Стоит добавить проверки на успешность системных вызовов
enum
{
BlockSize = 16,
}
int fds[4];
unsigned int sizes[4];
char **list = [ "Disk0", "Disk0", "Disk0", "Disk0" ];
void
Ini_Raid0(void)
{
struct stat st;
for (int i = 0; i < 4; ++i) {
fds[i] = open(list[i], O_RDWR);
lstat(list[i], &st);
sizes[i] = st.st_size;
if (i != 0) {
sizes[i] += sizes[i - 1];
}
}
return;
}
void
Read_Raid0(int num, char *buf)
{
unsigned int byte = num * BlockSize;
int now_disk = 0;
for (int i = 0; i < BlockSize; ++i) {
while (byte > sizes[now_disk]) {
now_disk++;
}
if (now_disk > 3) {
_exit(1);
}
if (now_disk != 0) {
lseek(fds[now_disk], byte - sizes[now_disk - 1]);
} else {
lseek(fds[now_disk], byte);
}
read(fds[now_disk], 1, buf + i);
}
return;
}
+43
View File
@@ -0,0 +1,43 @@
#include <unistd.h>
#include <fcntl.h>
enum
{
BlockSize = 16,
}
int fds[4];
unsigned int sizes[4];
char **list = [ "Disk0", "Disk0", "Disk0", "Disk0" ];
void
Ini_Raid0(void)
{
struct stat st;
for (int i = 0; i < 4; ++i) {
fds[i] = open(list[i], O_RDWR);
lstat(list[i], &st);
sizes[i] = st.st_size / BlockSize;
if (i != 0) {
sizes[i] += sizes[i - 1];
}
}
return;
}
void
Read_Raid0(int num, char *buf)
{
int now_disk = 0;
int now_block = 0;
while (now_block != num) {
if (sizes[now_disk]
now_disk++;
now_block++;
now_disk %= 4;
}
return;
}
+35
View File
@@ -0,0 +1,35 @@
Что будет выведено на экран? Прокомментировать, почему? Если возможны несколько вариантов – привести все. Предполагается, что
обращение к функции вывода на экран прорабатывает атомарно и без буферизации. Все системные вызовы прорабатывают успешно.
Подключение заголовочных файлов опущено.
int main() {
int pid;
int fd[2];
char c = 'a';
pipe(fd);
if( (pid = fork()) > 0 ) {
read(fd[0], &c, 1);
kill(pid, SIGKILL);
wait(NULL);
} else {
putchar(c);
c = 'b';
write(fd[1], &c, 1);
c = 'c';
}
putchar(c);
return 0;
}
(Вес задачи: 2 балла)
Answer:
1) начнётся с a т.к. отец заблокируется на считывании
2) сын записал б в канал, дальше либо отец может отправить его "на убийство", либо сын проработает быстрее. У сына с
3) только после смерти сына отец выведет б
aсб
aб
+42
View File
@@ -0,0 +1,42 @@
Сколько раз система обратится к содержимому индексных дескрипторов при вызове: open("/dir1/dir2/dir3/file", O_RDONLY)?
Прокомментировать, почему? Считаем, что ни один из элементов пути к файлу не является символической ссылкой. (Вес задачи: 1 балл)
$$ Answer:
1) система будет последовательно пробегать по каждому из каталогов.
1) будет искать, есть ли файл в каталоге.
2) будет проверять, является ли сам файл каталогом.
2) сначала корень. ищем в нём dir1.<#> Первое обращение. Проверяем dir1 на каталог.<#> Второе обращение
find dir2 in dir1.<#> dir2 is dir?<#>
find dir3 in dir2.<#> dir3 is dir?<#>
find file in dir3.<#>
=> всего нам надо 7 обращений к содержимому индексных дескрипторов
$$ Ответ GPT:
При вызове open("/dir1/dir2/dir3/file", O_RDONLY) система обращается к индексным дескрипторам (inode) для каждого элемента пути.
Основные этапы:
Корневая директория /:
Первое обращение к индексному дескриптору (inode) — система обращается к inode корневого каталога /.
Директория dir1:
Второе обращение — система читает содержимое inode корневого каталога и ищет запись для dir1, после чего обращается к inode для dir1.
Директория dir2:
Третье обращение — система читает inode для dir1, затем ищет в его содержимом запись о dir2 и обращается к соответствующему inode.
Директория dir3:
Четвёртое обращение — система аналогично читает inode для dir2, находит запись для dir3 и обращается к inode для dir3.
Файл file:
Пятое обращение — система читает inode для dir3, находит запись о файле file и обращается к inode для файла.
Итог:
Таким образом, система обращается к содержимому индексных дескрипторов 5 раз (по количеству элементов пути /, dir1, dir2, dir3, file).
Почему:
Каждая директория в Unix-подобных файловых системах представлена как файл каталога, содержащий список файлов и подкаталогов.
Чтобы найти нужный файл, система последовательно открывает каждый inode, пока не доберётся до конечного файла.
+1
View File
@@ -0,0 +1 @@
cal
BIN
View File
Binary file not shown.
+54
View File
@@ -0,0 +1,54 @@
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int
return_bit_int(int *mas, int n)
{
unsigned int byte = mas[n / (sizeof(int) * 8)]; // (sizeof(int) * 8) == 32
int offset = 32 - 1 - n % 32;
return (byte & (1 << offset)) >> offset;
}
int
return_bit_byte(unsigned char *mas, int n)
{
unsigned int byte = mas[n / (sizeof(char) * 8)]; // (sizeof(char) * 8) == 8
int offset = 8 - 1 - n % 8;
return (byte & (1 << offset)) >> offset;
}
// пусть битовый массив записан в файл. Массив - свободные блоки ФС. Вывести максимальную длину свободных блоков.
int
main(int argc, char **argv)
{
int fd = open(argv[1], O_RDONLY);
int size = lseek(fd, 0, SEEK_END);
unsigned char *mas = malloc(size);
lseek(fd, 0, 0); // SEEK_CUR == 0, SEEK_SET == 1, SEEK_END == 2
for (int i = 0; i < size; ++i) {
read(fd, mas + i, 1); // читаем из файла массив
}
int max_len = 0;
int tmp = 0; // для хранения текущей длины
for (int i = 0; i < size * 8; ++i) { // пробегаем по всем битам
if (return_bit_byte(mas, i) == 1) {
tmp++;
} else {
max_len = (max_len > tmp) ? max_len : tmp;
tmp = 0;
}
}
max_len = (max_len > tmp) ? max_len : tmp; // если последний бит был 1, то надо доп проверку
printf("%d\n", max_len);
return 0;
}
+24
View File
@@ -0,0 +1,24 @@
// на вход подаётся имя каталога.
// пробежать рекурсивно по всему каталогу и папкам в нём. Если встретился регулярный файл с именем, которое
// заканчивается на .exeсute, открыть, прочесть путь, запустить по нему прогу.
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
int
main(int argc, char *argv[])
{
DIR *d = opendir(argv[1]);
struct dirent *dd;
while ((dd = readdir(d))) {
char str[PATH_MAX];
snprintf(str, PATH_MAX, "%s/%s", argv[1], dd->d_name);
write(1, str, strlen(str));
write(1, "\n", 1);
}
return 0;
}
+42
View File
@@ -0,0 +1,42 @@
// на вход подаётся имя каталога.
// пробежать рекурсивно по всему каталогу и папкам в нём. Если встретился регулярный файл с именем, которое
// заканчивается на .exeсute, открыть, прочесть путь, запустить по нему прогу.
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
int
main(int argc, char *argv[])
{
DIR *d = opendir(argv[1]);
struct dirent *dd;
struct stat st;
while ((dd = readdir(d))) {
if (strcmp(dd->d_name, ".") == 0 || strcmp(dd->d_name, "..") == 0) {
continue;
}
char str[PATH_MAX];
snprintf(str, PATH_MAX, "%s/%s", argv[1], dd->d_name);
lstat(str, &st);
if (S_ISREG(st.st_mode) && st.st_size < strtol(argv[2], NULL, 10)) {
if (strlen(str) >= 8 && strcmp(str + strlen(str) - 8, ".execute") == 0) {
int fd = open(str, O_RDONLY);
char s[PATH_MAX + 1];
// memset(s, 0, PATH_MAX);
s[read(fd, s, PATH_MAX)] = '\0';
if (!fork()) {
execlp(s, s, NULL);
_exit(1);
}
close(fd);
}
}
}
return 0;
}
+43
View File
@@ -0,0 +1,43 @@
#include <unistd.h>
#include <fcntl.h>
enum
{
BlockSize = 16,
}
int fds[4];
unsigned int sizes[4];
char **list = [ "Disk0", "Disk0", "Disk0", "Disk0" ];
void
Ini_Raid0(void)
{
struct stat st;
for (int i = 0; i < 4; ++i) {
fds[i] = open(list[i], O_RDWR);
lstat(list[i], &st);
sizes[i] = st.st_size / BlockSize;
if (i != 0) {
sizes[i] += sizes[i - 1];
}
}
return;
}
void
Read_Raid0(int num, char *buf)
{
int now_disk = 0;
int now_block = 0;
while (now_block != num) {
if (sizes[now_disk]
now_disk++;
now_block++;
now_disk %= 4;
}
return;
}
+33
View File
@@ -0,0 +1,33 @@
#include <unistd.h>
#include <fcntl.h>
enum
{
BlockSize = 16,
}
int fds[5];
void
Write_Raid4(int num, char *buf)
{
unsigned char tmp1[BlockSize];
unsigned char tmp2[BlockSize];
int num_disk = num % 4;
lseek(fd[num_disk], num * BlockSize);
lseek(fd[4], num * BlockSize);
read(fd[num_disk], tmp1, BlockSize);
read(fd[4], tmp2, BlockSize);
for (int i = 0; i < BlockSize; ++i) {
tmp2[i] ^= tmp1[i];
tmp2[i] ^= buf[i];
}
lseek(fd[num_disk], num * BlockSize);
lseek(fd[4], num * BlockSize);
write(fd[num_disk], buf, BlockSize);
write(fd[4], tmp2, BlockSize);
return;
}
+24
View File
@@ -0,0 +1,24 @@
// суть - предсказываем поведение кэша.
#include <stdio.h>
#include <string.h>
enum
{
CACHE_LEN = 1024,
BLOCK_SIZE = 512,
};
int
main(void)
{
unsigned addrs[CACHE_LEN];
memset(addrs, -1, CACHE_LEN);
unsigned addr, cnt = 0;
while (scanf("%u", &addr) == 1) {
int i = (addr / BLOCK_SIZE) % CACHE_LEN;
cnt += (addrs[i] != -1) && (addrs[i] != addr);
addrs[i] = addr;
}
}
+38
View File
@@ -0,0 +1,38 @@
#include <unistd.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <fcntl.h>
struct record
{
double dbl, int num,
}
int
main(int argc, char **argv)
{
int shm_key = shmget(IPC_PRIVATE, sizeof(record), IPC_CREAT | 0666);
int sem_key = semget(IPC_PRIVATE, 1, IPC_CREAT | 0666);
record *mem = shmat(shm_key, NULL, 0);
for (int i = 1; i < argc; ++i) {
int fd = open(argv[i], O_RDONLY);
double sum = 0;
int num = 0;
double tmp;
while (read(fd, &tmp, sizeof(tmp)) {
num++;
sum += tmp;
}
semop(sem_key, &(struct sembuf){.sem_num = 0, .sem_op = -2}, 1);
*mem = (struct record){.dbl = sum, .num = num};
semop(sem_key, &(struct sembuf){.sem_num = 0, .sem_op = -1}, 1);
}
while (wait(NULL) != -1) {
}
return 0;
}
Executable
+54
View File
@@ -0,0 +1,54 @@
#include <stdio.h>
#include <unistd.h>
#include <wait.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <sys/file.h>
int main(int argc, char** argv){
int id_of_shm = shmget(argv[1], sizeof(double) * 2, IPC_CREAT | 0666);
float* start_of_shm = shmat(id_of_shm, NULL, 0);
int sem_id = semget(IPC_PRIVATE, 1, IPC_CREAT | 0666);
semctl(sem_id, 0, SETVAL, 1);
struct sembuf p = {0, -1, 0}, v = {0,1,0};
for(int i = 2; i < argc; i++){
pid_t pid = fork();
if (pid == 0) {
FILE* in_file = fopen(argv[i], "r");
float sum = 0, n = 0;
float buf;
while(fscanf(in_file, "%f", &buf) != EOF){
sum += buf;
n++;
}
semop(sem_id, &p, 1);
start_of_shm[1] += sum;
start_of_shm[0] += n;
semop(sem_id, &v, 1);
fclose(in_file);
return 0;
}
}
while (wait(NULL) != -1 ){
}
printf("%f\n", start_of_shm[1] / start_of_shm[0]);
semctl(sem_id, 0, IPC_RMID);
shmctl(id_of_shm, IPC_RMID, NULL);
return 0;
}
Executable
+41
View File
@@ -0,0 +1,41 @@
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
volatile int counter = 0;
volatile int signals = 0;
int fd2;
void handler(int sig) {
++signals;
if (signals < 3) {
printf("%d\n", counter / 2);
} else {
lseek(fd2, 0, SEEK_SET);
char buf;
while (read(fd2, &buf, 1) > 0) {
write(1, &buf, 1);
}
exit(0);
}
}
int main(int argc, char** argv) {
signal(SIGINT, handler);
int fd1 = open(argv[1], O_RDONLY, 0666);
fd2 = open(argv[2], O_CREAT | O_WRONLY);
char buf;
while (read(fd1, &buf, 1) > 0) {
if (counter % 2 == 0) {
write(fd2, &buf, 1);
}
++counter;
}
return 0;
}
Executable
+39
View File
@@ -0,0 +1,39 @@
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <string.h>
int
main(int argc, char **argv)
{
int fd[2];
pipe(fd);
if (!fork()) {
close(fd[1]);
dup2(fd[0], 0);
execlp("wc", "wc", NULL);
_exit(1);
}
close(fd[0]);
int file = open(argv[1], O_RDONLY);
char test = argv[2][0];
char buf[8];
while (read(file, buf, 8) == 8) {
if (buf[0] != test) {
continue;
}
printf("%s\n", buf);
write(fd[1], buf, 8);
}
close(fd[1]);
while (wait(NULL) != -1)
;
return 0;
}
Executable
+34
View File
@@ -0,0 +1,34 @@
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <string.h>
int
main(int argc, char **argv)
{
int file = open(argv[1], O_RDONLY);
int file_out = open("tmp", O_WRONLY | O_CREAT | O_TRUNC, 0666);
dup2(file, 0);
dup2(file_out, 1);
char buf[101];
while (fgets(buf, 100, stdin) != NULL) {
for (int i = 0; i < strlen(buf); i++) {
if (!strncmp(buf + i, "begin", 5)) {
printf("{");
i += 4;
} else if (!strncmp(buf + i, "end", 3)) {
printf("}");
i += 2;
} else {
printf("%c", buf[i]);
}
}
}
rename("tmp", argv[1]);
return 0;
}

Some files were not shown because too many files have changed in this diff Show More