0% found this document useful (0 votes)
4 views11 pages

Script

The document discusses various applications of sequential files in programming, including data logging, configuration files, data serialization, text file processing, and backup and archiving. It also covers common programming errors such as syntax, logical, and runtime errors, along with debugging techniques like print statements, code reviews, and rubber duck debugging. Each section includes code examples to illustrate the concepts and methods for fixing errors.

Uploaded by

jubahib.jane23
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views11 pages

Script

The document discusses various applications of sequential files in programming, including data logging, configuration files, data serialization, text file processing, and backup and archiving. It also covers common programming errors such as syntax, logical, and runtime errors, along with debugging techniques like print statements, code reviews, and rubber duck debugging. Each section includes code examples to illustrate the concepts and methods for fixing errors.

Uploaded by

jubahib.jane23
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Recap - Juliana

Exploring real-world applications of sequential files


Data Logging - Adi
Application:
• System Monitoring: Sequential files are used to log system events, errors, and
performance metrics. This is essential for troubleshooting, monitoring, and maintaining
systems.
Example:
• Web Server Logs: A web server logs each request, response time, and error messages
in a sequential file, which can be analyzed to diagnose issues and optimize
performance.
Code Example:
#include <stdio.h>
#include <time.h>

int main() {
FILE *logFile = fopen("[Link]", "a");
if (logFile == NULL) {
printf("Error opening log file.\n");
return 1;
}

time_t currentTime = time(NULL);


fprintf(logFile, "Request received at %s", ctime(&currentTime));

fclose(logFile);
return 0;
}

● This C code logs a timestamp indicating when a request is received and appends it to a
file named "[Link]."\
● FILE *logFile = fopen("[Link]", "a"); This opens the file [Link] in append
mode ("a"). If the file doesn't exist, it will be created. If it exists, data will be added at the
end of the file.
● if (logFile == NULL) {
printf("Error opening log file.\n");
return 1;
} If fopen() fails (for example, due to permission issues), logFile will be NULL. In
such a case, an error message is printed, and the program exits with a non-zero return value.
● time_t currentTime = time(NULL); time(NULL) gets the current time and stores it in
currentTime
● fprintf(logFile, "Request received at %s", ctime(&currentTime));
ctime(&currentTime) converts the currentTime (which is of type time_t) to a human-
readable string representing the time.
fprintf writes this formatted string to logFile.
● fclose(logFile);This closes the logFile after writing, ensuring that all data is saved and
the file handle is released.

Configuration Files - Adi


Application:
• Application Settings: Sequential files are used to store configuration settings for
applications. These files contain parameters that define how the application behaves.
Example:
• Database Connection Strings: Configuration files that store database connection
details such as host, port, username, and password.
Code Example:
#include <stdio.h>

int main() {
FILE *configFile = fopen("[Link]", "w");
if (configFile == NULL) {
printf("Error opening configuration file.\n");
return 1;
}

fprintf(configFile,
"Host=localhost\nPort=5432\nUser=admin\nPassword=secret\n");

fclose(configFile);
return 0;
}

● The program opens the file [Link] in write mode ("w"). If the file doesn't exist, it
will be created. If it exists, it will be overwritten.
● If fopen() fails, an error message is printed, and the program exits with a return value
of 1.
● The fprintf() function writes the configuration settings to the [Link] file in the
specified format. This includes the host, port, user, and password.
● fclose() is used to close the file after writing, ensuring the changes are saved.
Data Serialization - Allen
Application:
• Storing Program Data: Sequential files are used to serialize program objects or data
structures, making it easy to save and load the state of an application.
Example:
• Saving User Preferences: A program saves user preferences or session data to a file,
which can be loaded the next time the user starts the application.
Code Example:
#include <stdio.h>

typedef struct {
int userId;
float balance;
} UserData;

int main() {
FILE *dataFile = fopen("user_data.dat", "wb");
if (dataFile == NULL) {
printf("Error opening data file.\n");
return 1;
}

UserData user = {123, 456.78};


fwrite(&user, sizeof(UserData), 1, dataFile);

fclose(dataFile);
return 0;
}

● The program opens the file user_data.dat in binary write mode ("wb"). If the file
doesn't exist, it will be created. If it exists, it will be overwritten.
● If fopen() fails to open the file, an error message is printed, and the program exits with
a return value of 1.\
● The program initializes a UserData structure with userId = 123 and balance =
456.78.
● The fwrite() function is used to write the user data (in binary format) to the file. It
writes the data from the address of user, the size of the UserData structure, and the
number of items (1 in this case) to the file.
● fclose() is called to close the file after writing, ensuring that all data is properly saved
and the file handle is released.

Text File Processing - Allen


Application:
• Text Analysis and Manipulation: Sequential files are often used for processing text
files for tasks such as parsing, data extraction, and content analysis.
Example:
• Data Extraction: A script processes a log file to extract and analyze specific
information, such as error rates or usage statistics.
Code Example:
#include <stdio.h>

int main() {
FILE *textFile = fopen("[Link]", "r");
if (textFile == NULL) {
printf("Error opening text file.\n");
return 1;
}

char line[256];
while (fgets(line, sizeof(line), textFile)) {
printf("%s", line);
}

fclose(textFile);
return 0;
}

● fopen("[Link]", "r") opens the [Link] file in read mode ("r"). If the file
doesn't exist or can't be opened, the program prints an error message and exits with a
non-zero value (1).
● char line[256]; defines a character array to hold each line from the file. Each time
the program reads a line, it stores the content in this array.
● fgets(line, sizeof(line), textFile) reads a line from textFile into the
line array, up to a maximum of 255 characters (leaving space for the null terminator).
● The while loop continues as long as fgets() successfully reads a line from the file.
Each line is then printed to the console using printf("%s", line).
● After reading all lines, fclose(textFile) is used to close the file and release the file
handle.

Backup and Archiving - Yen


Application:
• Data Backup: Sequential files are used to create backups of critical data. These
backups are stored in a sequential format for easy restoration.
Example:
• Database Backup: A database system periodically creates a sequential file backup of
the database to ensure data integrity and availability.
Code Example:
#include <stdio.h>
#include <string.h>

int main() {
FILE *sourceFile = fopen("data_original.txt", "r");
FILE *backupFile = fopen("data_backup.txt", "w");

if (sourceFile == NULL || backupFile == NULL) {


printf("Error opening file.\n");
return 1;
}

char buffer[256];
while (fgets(buffer, sizeof(buffer), sourceFile)) {
fputs(buffer, backupFile);
}

fclose(sourceFile);
fclose(backupFile);

return 0;
}

The program opens two files:

● data_original.txt in read mode ("r") for reading the original data.


● data_backup.txt in write mode ("w") to create or overwrite the backup file.
● If either file cannot be opened (e.g., due to missing files or permission issues), the
program prints an error message and exits with a status code of 1.
● char buffer[256]; defines a buffer to store each line read from the source file.
● The buffer is used as a temporary storage area to hold data that is read from the source
file (data_original.txt) one line at a time.
● fgets(buffer, sizeof(buffer), sourceFile) reads a line from the source file
and stores it in buffer.
● fputs(buffer, backupFile) writes the contents of buffer to the backup file.
● The while loop continues until fgets() returns NULL, indicating the end of the file.
● After copying all data, the program uses fclose() to close both the source and backup
files, ensuring that all data is properly saved and resources are released.

Identifying and fixing common programming errors


a. Syntax Errors - Yen
A syntax error occurs when the code violates the rules of the programming language, such as
missing semicolons, unmatched brackets, or incorrect function calls. These errors prevent the
program from compiling or running.
Examples:
• Missing semicolons, mismatched parentheses, incorrect keywords.
How to Fix:
• Carefully review error messages provided by the compiler or interpreter.
• Check for common syntax issues like missing semicolons or parentheses.
• Use an IDE or editor with syntax highlighting to spot mistakes easily.
Code Example:

#include <stdio.h>

int main() {
printf("Welcome to Programming!") // Missing semicolon
return 0 // Missing semicolon
}

Fixed Code

#include <stdio.h>

int main() {
printf("Welcome to Programming!"); // Semicolon added
return 0; // Semicolon added
}

● The original code was missing a semicolon (;) after the printf function call. In C,
every statement must end with a semicolon, otherwise the compiler will throw an error.
● The corrected version adds the missing semicolon, which allows the program to compile
and run correctly. The program now prints Welcome to Programming! to the console
and returns 0 to indicate successful execution.

b. Logical Errors - MJ
Logical errors occur when the program compiles and runs but produces incorrect results due to
flawed logic in the code. These are harder to detect because they don't generate syntax or
runtime errors.
Examples:
• Incorrect calculations, improper use of conditional statements.
Steps to Fix:
1. Carefully review the logic and flow of the program.
2. Use debugging tools or insert print statements to trace variable values and program
execution.
3. Validate formulas and conditions to ensure correctness.
Code Example:

Code with error


#include <stdio.h>

int main() {
int num = 5;
if (num = 10) { // Assignment instead of comparison
printf("Number is 10.\n");
} else {
printf("Number is not 10.\n");
}
return 0;
}

Fixed Code
#include <stdio.h>

int main() {
int num = 5;
if (num == 10) { // Correct comparison operator
printf("Number is 10.\n");
} else {
printf("Number is not 10.\n");
}
return 0;
}

● The condition if (num = 10) uses the assignment operator (=) instead of the
comparison operator (==).
● This means that num is assigned the value 10 during the evaluation of the if statement.
The result of the assignment is the value that num was assigned, which is 10 (a non-
zero value).
● In C, any non-zero value is treated as true, so the if statement will always execute the
true branch (printf("Number is 10.\n");), even if num was initially 5.
c. Runtime Errors - MJ
A runtime error occurs while the program is running, causing it to crash or behave
unpredictably. Common causes include dividing by zero, accessing invalid memory locations,
using
uninitialized variables, or opening nonexistent files.
Examples:
• Accessing null pointers, dividing by zero.
Steps to Fix:
1. Validate user input and handle invalid inputs gracefully.
2. Use error-checking mechanisms like if conditions to prevent invalid operations.
3. Debug using tools or print statements to identify the cause of the crash.
4. Implement exception handling (if supported by the language).
Code Example:

Code with Error


#include <stdio.h>

int main() {
int a = 10, b = 0;
printf("Result: %d\n", a / b); // Division by zero causes a runtime error
return 0;
}

Fixed Code
#include <stdio.h>

int main() {
int a = 10, b = 0;
if (b != 0) {
printf("Result: %d\n", a / b);
} else {
printf("Error: Division by zero is not allowed.\n");
}
return 0;
}

● The original code attempts to divide a by b where b is 0.


● Division by zero is undefined in mathematics, and in C programming, it leads to a
runtime error or undefined behavior. The program will crash or produce unpredictable
results when attempting this division.
● To avoid division by zero, you should check if b is 0 before performing the division.
● The program now checks if b is not equal to 0 using the condition if (b != 0).
● If b is non-zero, it safely performs the division and prints the result.
● If b is zero, it enters the else block and prints an error message ("Error: Division
by zero is not allowed."), preventing a runtime error from occurring.

Introduction to debugging techniques and tools


a. Debugging Techniques - Dennis

● Print statements are used in the code that shows the values of variables or follow what
the program is doing at different times while it runs. This method helps in checking the
internal state of the program and how it acts step by step.
● Usage: Print statements are helpful in the development or debugging phase of coding.
They help developers to track how variables change over time, check whether specific
blocks of code are executed, and check whether program logic is correct.

Example:

#include <stdio.h>

int main() {
int a = 5, b = 10;
printf("Initial values -> a: %d, b: %d\n", a, b); // Debugging statement
int sum = a + b;
printf("Sum of a and b: %d\n", sum); // Debugging statement
return 0;
}

Explanation:

● The print statements show the starting values of a and b, followed by displaying the total
of those values. This comes in handy for checking that each stage of the program is
running as one intended.

Code Review:
● Description: Code review is sharing your code with a peer or colleague for review.
During review, the reviewer looks for logical errors, possible issues, and places where
the code may be optimized. This process helps in identifying some issues that the
original programmer may overlook.
● Usage: Code reviews are a good practice in software development. They provide the
code with a new kind of view. They help people work together, make the code better and
decrease chances of unseen mistakes.

Example:

● A code review can check whether the logic in a loop is correct, whether variables have
good names, whether functions are organized and clearly explained, and whether there
is no security risk such as a buffer overflow.
Steps in a Code Review:

1. Understand the Purpose: Make sure the reviewer knows what the code is intended to
do.
2. Analyze Structure: Verify that the code is logically structured and adheres to coding
standards.
3. Check Functionality Run the code above to test it for functionality.
4. Suggest Improvements: Find areas that can be made better for improved performance
and easier reading.

Rubber Duck Debugging:


● Explaining your code and problem to something that does not think, like a rubber duck,
helps you understand yourself better. Talking over the problem this way helps put your
thoughts in order and often finds the solution.
● This technique is on the principle that while you teach or explain something, it helps you
understand the problem also. Going through it one line at a time might help you see
mistakes or issues that you did not notice before.

Example:

● Situation: You are trying to debug a function that should compute the sum of two
numbers but is giving incorrect answers.
● Rubber Duck Debugging: As you explain to the duck, you realize that you forgot to
initialize one of the variables before using it in the calculation.

Steps in Rubber Duck Debugging:

1. Describe the Code: Explain each component of the code as if speaking out loud to
someone.
2. Explain Your Thinking: Describe what you thought each part of the code would do and
what really happened.
3. Find the Problem: Typically discussing the problem can help you see what is really
causing it.

Unit Testng:
● Unit testing is about writing tests for small parts or functions of code to ensure that they
behave in the manner they are expected to. Mostly, unit tests concentrate on some small
chunk of the program, keeping it isolated from the remaining code of the system. Such
tests reveal bugs early on and avoid introducing new bugs into the code.
● Usage: Unit testing is often used in software development to ensure that the code works
well and to help with future changes. Running tests after making changes can be used to
check that the new code does not cause any problems with what already works.
Example:

#include <assert.h>
#include <stdio.h>

int add(int a, int b) {


return a + b;
}

void testAddition() {
assert(add(2, 3) == 5); // Test for correct addition
assert(add(-1, 1) == 0); // Test for adding negative numbers
assert(add(0, 0) == 0); // Test for adding zero
printf("All tests passed!\n");
}

int main() {
testAddition(); // Running the unit tests
return 0;
}

Explanation:

● The add function performs addition directly of two numbers.


● This testAddition function carries several tests. It's by way of the assert function to check
whether the add function works properly in various situations. An assert checks if the
enclosed statement is true or not; it terminates the program and gives an error message
if it isn't. If everything goes right, the program displays "All tests passed!". Steps of Unit
Testing: Write Test Cases: Identify input values and what the results should be for the
function being tested. Run the Tests: Call the unit tests to ensure this function correctly
executes at any given time. Analyze Results. If the test fails then debug and correct the
function, and run tests again

Steps in Unit Testing:

1. Write Test Cases: Define input values and expected outputs for the function being
tested.
2. Run the Tests: Execute the unit tests to see if the function works correctly for all cases.
3. Analyze Results: If a test fails, debug and fix the function, then rerun the tests

b. Debugging Tools - Denver

You might also like