---
# System prepended metadata

title: Lab&HW 12 File I/O & Low-level Programming

---

# Lab&HW 12 File I/O & Low-level Programming

[TOC]

## Forum Link

https://hackmd.io/1YXqOPoZT8KmfB8UOPFwow

## Lab 12-1 Remove duplicate and sort

**Notice!!!! You Are NOT ALLOW TO USE ARRAY IN THIS LAB**

In this exercise, you need to try to remove duplicate numbers from a given long list of numbers and print out the sorted result. 

The common way to solve it is to divide the problem into two steps: 
1. `remove duplicate` 
2. `sort`

However, in this exercise our data situation is very special. The size of each number is between 0 and 63, and the amount of data is larger than 10^7. 

![c-programming-practice-image-exercise-12](https://hackmd.io/_uploads/HyyXTRqI6.svg)

### **Lab 12-1 requirements**

#### Input
```
The input contains t numbers n[i]
where
    0 < t < 2 * 10^7
    0 < n[i] ≤ 63
```

#### Output
```
The output contains o numbers n[i]
where
    0 < o < t
    0 < n[i] ≤ 63
```

#### Sample Input
```
39 49 42 62 34 51 42 45 43 43 
```

#### Sample Output
```
34 39 42 43 45 49 51 62 
```

## Lab12-2 Server Log Summary Program

Write a C program that performs the following tasks:

1. File Reading: Open a log file named "server_log.txt" in read mode. Assume this log file contains lines of text, where each line represents a log entry with a date, time, and a message (e.g., "2023-12-17 10:30:00 Server Started").
2. Data Processing: Extract the date and time from each log entry and count the number of log entries for each unique date.
3. File Writing: Create a new file named "log_summary.txt" and write the summary of log entries for each date. The summary should include the date and the number of log entries for that date.
4. Error Handling: Ensure your program handles the case where "server_log.txt" does not exist or is empty, and display an appropriate message.
5. Closing Files: Close both the input and output files properly.

### Notice!!! 

The Lab12-2 should be submitted to [File Uploader](https://icp-file-uploader.cerana.tech/)

The name of your file should be `main.c`

### **Lab12-2 requirement**

You just have to demonstrate the five requirements described above to the TA using sample input, then submit it to the File Uploader and E3. 

You should use `diff` or `vimdiff` to show the TA that your result is correct

Reference: [File I/O](https://www.tutorialspoint.com/cprogramming/c_file_io.htm)
You may want to use fopen(), fclose(), fprintf(), fscanf()

```
// 助教會檢查什麼？
1. 把 server_log.txt 刪掉嘗試，要跳出錯誤訊息 “Error: Unable to open server_log.txt”
2. 把 server_log.txt 放在同目錄下面，執行出來的結果要跟 log_summary.txt 中
3. 你沒有用 fscanf 而是直接把答案 print 出來可以明年再見了 ^_^
```

#### Input file

```
The input file "server_log.txt" would typically contain lines with timestamps and log messages, formatted like "YYYY-MM-DD HH:MM:SS <message>". Each line represents an event, such as a server start, user login, or system update.
```

#### Output file

```
The output file "log_summary.txt" generated by the C program will summarize the number of log entries per day. Each line in this file will follow the format "YYYY-MM-DD: [Number of log entries]" and will only include dates that appear in the input file, listing how many log entries occurred on each date.
```

#### Sample input file

```
// server_log.txt
2023-12-17 10:30:00 Server Started
2023-12-17 11:00:25 User login successful
2023-12-17 11:15:45 Data update completed
2023-12-18 09:05:10 Maintenance mode enabled
2023-12-18 10:20:00 Server Restarted
2023-12-18 10:30:00 New user registered
```

#### Sample output file

```
// log_summary.txt
2023-12-17: 3 log entries
2023-12-18: 3 log entries
```

## Hw12-1 Simple Scheduler with Priority

In this problem, you are to implement a simple task scheduler. Each task has a unique name and a priority. The priority is an integer between 0 and 31, where 31 is the highest priority and 0 is the lowest priority.

Your scheduler should be able to handle the following operations:

* Insert a new task.
* Execute and remove the current highest priority task.
* In this exercise the task with same priority should be FILO(First In Last Out)

**Note:** 
This homework is the very simplified version of scheduler. When designing production level scheduler, you should consider more details such as expire time, response time, throughput, fairness, etc. If you want to know how linux kernel perform task scheduling, you can consider reading this article about the implementation of O(1) scheduler.

Worth reading: [The Linux Scheduling Algorithm](https://litux.nl/mirror/kerneldevelopment/0672327201/ch04lev1sec2.html)

### **Hw12-1 requirement**

#### Input
```
There is N lines (1 ≤ N ≤ 500,000), describing the operations. There are two types of operations:

insert <name> <priority>: Indicates inserting a task named name with a priority of priority (name is a string of no more than 20 characters, priority is an integer between 0 and 31).
execute: Indicates executing and removing the current highest priority task.
```

#### Output

```
For each execute operation, output the name of the task being executed. 

If there are no tasks to execute, output `No tasks to execute.`

If there are remaining task in queue, you should execute the rest of them before the program stop. 
```

#### Sample Input 1
```
insert 5 Task1
insert 10 Task2
execute
execute
```

#### Sample Output 1

```
Executing task: Task2 with priority 10
Executing task: Task1 with priority 5
```

#### Sample Input 2

```
insert 33 InvalidTask
execute
```

#### Sample Output 2

```
Invalid task priority: 33
No tasks to execute.
```

## Homework 12-2: Debug Report

**Assignment:**

Please refer to the code in the file HW12_Debugger.c, which has been posted on e3. Your task is to identify any potential memory leaks in the program.


**Restrictions:**

You are not permitted to add or delete any lines of code. You only need to pinpoint the locations that may cause memory leaks and explain how to fix them.

There are more than one places in the code that could lead to memory leaks. Please specify at least 2 locations and describe the necessary modifications for more robust memory management.

**Response template:**

You don't have to use GDB to debug, but please tell me how you found out the problem. 

> **Problems**
> Line **<number>**: **<your explanation>**
> Line **<number>**: **<your explanation>**
    > 
> **How I found the problems**
> 我這樣這樣，再那樣那樣，發現這樣這樣
    
**Code:**
```cpp
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int id;
    char *name;
} Student;

Student* createStudent(int id, const char *name) {
    Student *newStudent = (Student*)malloc(sizeof(Student));
    if (newStudent == NULL) {
        return NULL; // Memory allocation error
    }

    newStudent->id = id;
    newStudent->name = (char*)malloc(100 * sizeof(char));
    if (newStudent->name == NULL) {
        return NULL;
    }
    snprintf(newStudent->name, 100, "%s", name);
    return newStudent;
}

void processStudents(int count) {
    for (int i = 0; i < count; i++) {
        Student *s = createStudent(i, "StudentName");
        // Some processing with the student 's'
        printf("Processing student %d: %s\n", s->id, s->name);
    }
}

int main() {
    processStudents(5);
    printf("Students processed\n");
    return 0;
}
```

## Submission
Compress your lab & homework to `.zip` file
- lab
```
{student_id}_lab12
├── {student_id}_lab12-1
|   └──{student_id}_lab12-1.c
└── {student_id}_lab12-2
    └──main.c
    
```
compress `{student_id}_lab12` to `{student_id}_lab12.zip` and submit to e3
- homework
```
{student_id}_hw12
├── {student_id}_hw12-1
|   └──{student_id}_hw12-1.c
└── {student_id}_hw12-2
    └──{student_id}_hw12-2.pdf
```
compress `{student_id}_hw12` to `{student_id}_hw12.zip` and submit to e3

![](https://hackmd.io/_uploads/HJ8iRH9Za.png)

---