0% found this document useful (0 votes)
7 views

Unix Report

Uploaded by

coyog64466
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Unix Report

Uploaded by

coyog64466
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

VISVESVARAYA TECHNOLOGICAL UNIVERSITY

JNANA SANGAMA, BELAGAVI-590018

UNIX SYSTEM PROGRAMMING (BCS515C)

REPORT ON

“WEATHER FETCHER”
Submitted in partial fulfilment of the requirements for the 5th Semester
INFORMATION SCIENCE AND ENGINEERING
Submitted by
HANSIKA S V 1BI22IS033
HARISH CHANDRA THAKUR 1BI22IS034
INDU GULAPALYAM 1BI22IS035
HEMANTH M P 1BI22IS036

Under the Guidance of

DR. ROOPA H
Associate Professor

Department of ISE

BIT, Bangalore

DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING


BANGALORE INSTITUTE OF TECHNOLOGY
K R Road, V.V Puram, Bengaluru-560004
2024-2025
TABLE OF CONTENTS

CHAPTER PAGE
DESCRIPTION
NO. NO.
1 INTRODUCTION 1-2

1.1 General Overview 1

1.2 Objectives 1

1.3 Existing System 1

2 PROBLEM STATEMENT 3

3 PROPOSED SOLUTION 4-5

4 IMPLEMENTATION 6-10

4.1 Methods 6

4.2 Shell Scripting Approach 6

4.2.1 Implementation 6

4.2.2 Source Code 7

4.3 System Programming Approach 8

4.3.1 Implementation 8

4.3.2 Source Code 9

4.3.3 Main Code 9

5 RESULTS 11-12

5.1 Shell Scripting 11

5.2 System Programming 12

6 CONCLUSION 13

REFERENCES 14
LIST OF FIGURES

FIGURE PAGE
DESCRIPTION
NO. NO.
Figure 1.1 Weather Fetcher using UNIX 2

Figure 3.1 System Flowchart 4

Figure 5.1 Weather Fetching using shell script 11

Figure 5.2 Invalid choice 11

Figure 5.3 Weather Fetching using system programming 12

Figure 5.4 Exiting 12


CHAPTER 1
INTRODUCTION

1.1 General Overview

A Weather Fetcher is a tool or application designed to retrieve and display weather information
by connecting to online weather data providers. It typically integrates with APIs such as
OpenWeatherMap or WeatherAPI, fetching real-time or forecasted data like temperature,
humidity, wind speed, and precipitation. Users can input location details such as city names,
ZIP codes, or geographic coordinates, with advanced systems sometimes offering GPS or IP-
based location detection. The fetched data, usually in JSON or XML format, is parsed and
displayed in a user-friendly manner through various interfaces, ranging from web or mobile
apps to command-line tools. Weather fetchers often include features like unit conversion, error
handling for invalid inputs or network issues, and periodic updates to ensure current
information. They are widely used in personal projects, smart devices, travel applications, and
forecasting tools, offering valuable insights for daily activities and decision-making.

1.2 Objectives
The primary objectives of the Weather Fetcher are:

• To provide accurate and real-time weather data by connecting to reliable weather APIs.
• To provide support for diverse location inputs such as city names, ZIP codes, or
geographic coordinates.
• To provide processed and structured weather information that is easy to read and
understand.
• To provide actionable weather insights for informed decision-making in various
applications.
• To provide user-friendly features like unit conversion, language options, and
customizable settings.

1.3 Existing System


1. OpenWeatherMap
• Free tier has limited API calls per minute.
• Data granularity can be insufficient for hyper-localized needs.

Dept. of ISE, BIT 2024-25 Page 1


WEATHER FETCHER

2. WeatherAPI
• Premium features (like advanced historical data) require costly subscriptions.
• The free tier has a limited number of API requests per month.
• User interface for setup can be complex for beginners.
3. wttr.in
• Limited customization of the data format.
• Does not provide advanced features like weather alerts or historical data.
• Relies on other APIs (like OpenWeatherMap) for data, which might inherit their
limitations.
4. AccuWeather API
• Subscription costs are high, especially for commercial use.
• Complex API structure compared to simpler alternatives.
• Overwhelming for users seeking basic weather data.
5. NOAA Weather Service
• Limited to U.S. regions for detailed data.
• Outdated or less user-friendly API compared to modern alternatives.
• Lacks the convenience of advanced developer features, such as SDKs or client libraries.

Figure 1.1 Weather Fetcher using UNIX

Dept. of ISE, BIT 2024-25 Page 2


CHAPTER 2
PROBLEM STATEMENT
In modern Weather Fetcher, access to reliable and timely weather information is crucial for
various personal, professional, and industrial applications. However, existing systems often
face significant challenges, such as high costs for premium features, limited accessibility for
non-technical users, and regional inconsistencies in data accuracy, particularly in underserved
areas. Strict API rate limits in free tiers further hinder scalability, while platform constraints
restrict usability across diverse devices. Additionally, many solutions lack flexibility for
customization and are resource-intensive, making them unsuitable for low-power or embedded
systems. These limitations highlight the need for a lightweight, user-friendly, and cost-effective
Weather Fetcher solution that delivers accurate, real-time data with wide accessibility,
scalability, and seamless integration capabilities across various platforms and environments.

Dept. of ISE, BIT 2024-25 Page 3


CHAPTER 3
PROPOSED SOLUTION
The Weather Fetcher combines the power of UNIX shell scripting and System programming
to create a robust solution. Key functionalities are divided between these two components:

Shell Scripting Features


1. Task Automation:
Automates repetitive tasks such as displaying candidates and collecting user input.
Uses commands like echo, read, and grep to manage data efficiently.
2. Data Security:
Protects sensitive voter information using controlled file access (superuser).
Validates inputs to prevent duplicate voting and unauthorized actions.
3. User-Friendly Output:
Formats results using commands like column and sort for better readability.

System Programming Features


1. File Handling:
Uses system calls like open(), read(), write(), and close() for managing data files.
2. Data Processing:
Validates voter credentials and candidate IDs using functions such as strcmp() and
sscanf().
3. Security Features:
Implements privilege checks using geteuid() to ensure only authorized users access
administrative features

Figure 3.1 System flowchart


Dept. of ISE, BIT 2024-25 Page 4
WEATHER FETCHER
1. Start the Program:
The program begins and waits for the user to input their choice.
2. Show Menu:
A menu is displayed with three options:
• Fetch weather using a shell script.
• Fetch weather using a C program.
• Exit the program.
3. User Makes a Choice:
The program checks the user's choice:
Option 1 (Shell Script):
• The program runs the shell script fetch_weather_shell.sh to fetch weather data
from the OpenWeatherMap API using curl.
• If the tool jq is available, the script parses the data and formats it into a readable
weather report.
• The report is displayed to the user.
Option 2 (C Program):
The program compiles the fetch_weather.c file using gcc.
The compiled C program is executed to:
• Fetch weather data using curl (via system calls).
• Parse the response using jq.
• Format and display the weather report to the user.:
Option 3 (Exit):
• The program terminates if the user selects this option.
4. Fetch Weather Data:
Both methods (shell script or C program) communicate with the OpenWeatherMap API
to retrieve weather details, such as:
• City name
• Temperature
• Humidity
• Weather description
• Wind speed
5. Display Weather Report:
The fetched data is formatted and shown to the user in an easy-to-read format.
6. End the Program:
The program ends when the user chooses to exit or after completing their weather query.

Dept. of ISE, BIT 2024-25 Page 5


CHAPTER 4
IMPLEMENTATION
4.1 Methods
1. Normal User:
• Fetch_basic_weather_data():Retrieves essential weather details such as city
name, temperature, humidity, weather description, and wind speed
• display_basic_weather_report():Formats and presents the weather details in a
clean and readable manner.
2. Super User:
• fetch_detailed_weather_data():Retrieves all available weather information,
including advanced parameters such as atmospheric pressure, visibility, feels-
like temperature, and extended forecasts.
• parse_extended_weather_data():Processes additional fields from the API
response to extract detailed weather metrics.
• display_detailed_weather_report():Formats and presents an enhanced
weather report with additional details, ensuring clarity and comprehensive
insight for super users.
• fetch_historical_weather_data():Provides access to past weather records for
analysis.
• fetch_forecast_weather_data():Retrieves multi-day weather forecasts for
planning and decision-making.

4.2 Shell Scripting Approach


4.2.1 Implementation
a. API Key and City:
• The script uses an API key (API_KEY) to authenticate requests to the
OpenWeatherMap API.
• The script fetches weather data for the specified city (CITY).
b. Fetching Weather Data:
• The script uses curl to send an HTTP GET request to the OpenWeatherMap
API and retrieve the weather data in JSON format.
c. Parsing JSON Response:
• The script uses the jq tool to parse the JSON response.

Dept. of ISE, BIT 2024-25 Page 6


WEATHER FETCHER

It extracts various weather details such as:

• temperature: The current temperature in Celsius.


• weather_description: A textual description of the weather (e.g., "clear
sky").
• humidity: The humidity percentage.
• wind_speed: The wind speed in meters per second.

d. -z (String Length Check): The -z option is used in conditional expressions to check if


a string is empty (zero length). It returns true if the string is empty (i.e., the string has
no characters).
e. -s (File Exists and Not Empty): The -s option is used in conditional expressions to
check if a file exists and is not empty. It returns true if the file exists and contains data.
f. -r (File Readable): The -r option checks if a file is readable (i.e., it has read
permissions).
g. -v: Enables verbose output (useful for debugging and tracing the execution of
commands).
4.2.2 Source Code

#!/bin/bash
API_KEY="0434b123c3c1ede00e552fbea991f112"
echo "Enter your city:"
read CITY
RESPONSE=$(curl -s "http://api.openweathermap.org/data/2.5/weather?q=$CITY&appi>
if [ -z "$RESPONSE" ]; then
echo "Error: Failed to fetch weather data. Please check your internet conne>
exit 1
fi
if command -v jq > /dev/null; then
echo "Weather Information:"
echo "$RESPONSE" | jq -r '. | "City: \(.name)\nTemperature: \(.main.temp)°C>
else
echo "Error: jq is not installed. Please install jq for formatted output."
exit 1
fi

Dept. of ISE, BIT 2024-25 Page 7


WEATHER FETCHER

4.3 System Programming Approach


4.3.1 Implementation
1.File Operations
• open( ): A system call that opens a file for reading or writing. In this case, it is used to
open the shell script file in read-only mode.
• Read( ): A system call that reads data from a file descriptor. It is used here to read the
content of the shell script.
• close( ): A system call used to close an open file descriptor.
2. main( )
The main( ) function runs the menu-driven interface for the user, prompting them to choose
between the two methods of fetching weather data or to exit.
Menu Display: The menu offers three options:
• Fetch weather using shell scripting.
• Fetch weather using system calls in a C program.
• Exit the program
3. Functions
• system( ): A library function that executes a shell command (in this case, to execute the
shell script or C program).
• gcc: A C compiler invoked through the system() call to compile the C program.
• exit( ): A function that terminates the program, optionally returning an exit status.
• perror( ): A function that prints an error message related to the last error that occurred
during a system call.
4. execute_shell_script()
• This function is responsible for executing a shell script (fetch_weather_shell.sh)
without displaying its content.
5. execute_c_program()
• This function compiles and runs the C program (fetch_weather.c) that fetches weather
data.

Dept. of ISE, BIT 2024-25 Page 8


WEATHER FETCHER

4.3.2 Source Code


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void fetch_weather_system_calls() { char city[50];
char api_key[] = "0434b123c3c1ede00e552fbea991f112";
char command[512];
char buffer[1024];
FILE *fp;
printf("Enter your city: ");
scanf("%49s", city); // Limit input to prevent buffer overflow
int ret = snprintf(command, sizeof(command),
"curl -s
\"http://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s&units=metric\" | jq -r '. |
\"City: \\(.name)\\nTemperature: \\(.main.temp)°C\\nDescription:
\\(.weather[0].description)\\nHumidity: \\(.main.humidity)%%\\nWind Speed:
\\(.wind.speed)m/s\"'",
city, api_key);
if (ret < 0 || ret >= sizeof(command)) {
fprintf(stderr, "Error: Command string is too long or an error occurred.\n");
return;
}
fp = popen(command, "r");
if (fp == NULL) {
printf("Failed to fetch weather data.\n");return;
}
printf("\nWeather Information:\n");
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
printf("%s", buffer);
}pclose(fp);
}int main() {
fetch_weather_system_calls(); return 0;
}

4.3.3 Main Code

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define BUFFER_SIZE 1024
int fd;
char buffer[BUFFER_SIZE];
fd = open("fetch_weather_shell.sh", O_RDONLY);
if (fd < 0) {
perror("Error opening shell script file");
exit(EXIT_FAILURE);
}

Dept. of ISE, BIT 2024-25 Page 9


WEATHER FETCHER
ssize_t bytes_read = read(fd, buffer, BUFFER_SIZE - 1);
if (bytes_read < 0) {
perror("Error reading shell script file");
close(fd);
exit(EXIT_FAILURE);
}
buffer[bytes_read] = '\0';
close(fd);
system("bash fetch_weather_shell.sh");
}
void execute_c_program() {
printf("Compiling the C program...\n");
if (system("gcc -o fetch_weather fetch_weather.c") != 0) {
fprintf(stderr, "Error compiling C program\n");
exit(EXIT_FAILURE);
}
printf("Executing the C program...\n");
if (system("./fetch_weather") != 0) {
fprintf(stderr, "Error executing C program\n");
exit(EXIT_FAILURE);
}
}
int main() {
int choice;
while (1) {
printf("\nWeather Dashboard:\n");
printf("1. Fetch weather using shell scripting\n");
printf("2. Fetch weather using system calls (C program)\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
execute_shell_script();
break;
case 2:
execute_c_program();
break;
case 3:
printf("Exiting...\n");
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}

Dept. of ISE, BIT 2024-25 Page 10


CHAPTER 5
RESULTS
5.1 Shell Scripting

Figure 5.1 Weather Fetcher Using Shell Script


Execution of shell script, Fetches weather data of input city

Figure 5.2 Invalid choice, try again


Invalid choice and one has to try again

Dept. of ISE, BIT 2024-25 Page 11


WEATHER FETCHER

5.2 System Programming

Figure 5.3 Weather Fetching Using System Programming

Execution of system programming, Fetches weather data of input city

Figure 5.4 Exiting

Exits from the particular program

Dept. of ISE, BIT 2024-25 Page 12


CHAPTER 6
CONCLUSION
The Weather Fetcher program is an efficient tool designed to retrieve and display weather data
in a user-friendly format. By integrating multiple methods—such as a shell script and a C
program—it ensures flexibility and robustness in fetching weather information from the
OpenWeatherMap API. With features tailored to different user roles, it provides basic weather
details for normal users, in-depth reports for super users, and safeguards against unauthorized
access. The program's design emphasizes usability, clarity, and reliability, making it a practical
solution for accessing real-time weather updates while demonstrating seamless integration of
shell scripting and C programming capabilities.

Applications

3. Weather Forecasting: Use weather fetchers to monitor and predict weather patterns,
helping to issue forecasts and warnings.

4. Travel and Tourism: Provide tourists with forecasts to help them plan activities based
on weather conditions.

5. Agriculture: Farmers use weather data to decide when to plant or harvest crops,
optimize irrigation schedules, and protect against extreme weather events.

6. Disaster Management and Safety: Authorities use weather fetchers to monitor


dangerous weather events (e.g., storms, hurricanes, floods) and take timely action for
public safety.

Future Scope
• Real-Time and Hyperlocal Forecasting: The growing number of Internet of Things
(IoT) devices, such as smart weather stations, sensors, and drones, will provide real-
time data at a granular level, enabling hyperlocal weather predictions.
• Enhanced Climate Change Monitoring: Weather-fetching systems will increasingly
track and analyze long-term climate changes, providing actionable insights for climate
change mitigation and adaptation strategies.
• Blockchain and Weather Data Security: Blockchain could be used to authenticate
and secure weather data, ensuring its reliability for industries that depend on it, such as
agriculture, insurance, and logistics.

Dept. of ISE, BIT 2024-25 Page 13


REFERENCES
[1] OpenWeatherMap API Documentation: The API endpoint and data structure (e.g.,
JSON format for weather data) were directly taken from the official OpenWeatherMap API
documentation. Https://openweathermap.org/api

[2] Books like "The C Programming Language" by Brian W. Kernighan and Dennis M.
Ritchie are foundational for these concepts.

[3] "Advanced Programming in the UNIX Environment" by W. Richard Stevens.

Page 14

You might also like