Chit chat

=======

Beginning to like spinach more and more.

Print a text document.
$ lp mafalde1
request id is hp-63 (1 file(s))
$ lpq
hp is ready and printing
Rank    Owner   Job     File(s)                         Total Size
active  eddie   63      mafalde1                        2048 bytes
$ lpq
hp is ready
no entries

Probably redo the linux install on the Pogoplug. Not the whole thing, just the file system.

——————————————————-

No, what is your video resolution from your monitor? May not seem important, unless you need to get a replacement monitor that will support your existing setup or you need to do some desktop video such as the command:

$ avconv -f alsa -i hw:1 -f x11grab -r 25 -s 1280×768 -i :0.0 -vcodec libx264 -threads 4 file.avi

In this case it is 1280×768. Of course you could use a smaller portion of the desktop to capture. So how do we find the desktop resolution. There are several ways. The least verbose:

$ xdpyinfo  | grep ‘dimensions:’
dimensions:    1280×768 pixels (338×203 millimeters)

But if you wanted more information try:

$ xrandr
Screen 0: minimum 320 x 200, current 1280 x 768, maximum 4096 x 4096
VGA-0 disconnected (normal left inverted right x axis y axis)
LVDS connected 1280×768+0+0 (normal left inverted right x axis y axis) 305mm x 183mm
1280×768       60.0*+
1280×720       59.9
1152×768       59.8
1024×768       59.9
800×600        59.9
848×480        59.7
720×480        59.7
640×480        59.4
S-video disconnected (normal left inverted right x axis y axis)

or you could use a gui tool.

Be sure to research avconv the replacement for ffmpeg.

——————————————————-

There are actually some really good programs for the non-gui environment.Some programs can be used in multiple areas too’

User applications

  • Links2, lynx, elinks – internet
  • Bashpodder – audio podcast collector
  • Alpine – email client
  • Irssi – inter relay chat
  • Centerim – instant messaging client
  • Oleo or Sc – spreadsheet
  • Vim, emacs, nani, joe, or a dozen other programs – word processing
  • Antiword – deals with office based documents
  • Putty – secure accessing tool
  • Screen -multiple seesion tool
  • Ledger – accounting (seems to be based on gnucash)
  • gpm, mc, synaptic, sed, awk, sort, ncurses, bash ,ssh, wget, curl
  • Sqllite, mysql, psql, plus man other – databases
  • Hnb – outliner to organize ideas
  •  freebasic, gcc, python, pgp, pgp-cli, perl and etc programming language tools.
  • Too many to list here – games. (i.e ninvaders)
  • Moc, aplay, mplayer, cmis and may others – music players
  • Espeak or Festival – voice synthesizer.
  • Nget and may others – news readers.
  • Cdrecord – cd buring program.
  • wird – nice calendar tool.

Network administrator tools

ping: Check end-to-end connectivity (RTT delay, jitter, packet loss) of a remote host with ICMP echo/reply. Useful to check system status and reachability.

hping: Network scanning and testing tool that can generate ICMP/TCP/UDP ping packets. Often used for advanced port scanning, firewall testing, manual path MTU discovery and fragmentation testing.

traceroute: Discover a layer-3 forwarding path from a local host to a remote destination host with TTL-limited ICMP/UDP/TCP probe packets. Useful to troubleshoot network reachability and routing problems.

mtr: A variation of traceroute which characterizes per-hop packet loss/jitter with running statistics. Useful to characterize routing path delays.

netcat/socat: A swiss army knife of TCP/IP networking, allowing to read/write byte streams over TCP/UDP. Useful to troubleshoot firewall policies and service availability.

dig: DNS troubleshooting tool that can generate forward queries, reverse queries, find authoritative name servers, check CNAME, MX and other DNS records. Can be instructed to query a specific DNS server of your choosing.

nslookup: Another DNS checking/troubleshooting tool. Works with all DNS queries and records. Can query a particular DNS server.

dnsyo: A DNS testing tool which checks DNS propagation by performing DNS lookup from over a number of open resolvers located across 1,500 different networks around the world.

lsof: Show information about files (e.g., regular files, pipes or sockets) which are opened by processes. Useful to monitor processes or users in terms of their open network connections or opened files.

iftop: A ncurses-based TUI utility that can be used to monitor in real time bandwidth utilization and network connections for individual network interfaces. Useful to keep track of bandwidth hogging applications, users, destinations and ports.

netstat: A network statistics utility that can show status information and statistics about open network connections (TCP/UDP ports, IP addresses), routing tables, TX/RX traffic and protocols. Useful for network related diagnosis and performance tuning.

tcpdump: A popular packet sniffer tool based on libpcap packet capture library. Can define packet capturing filters in Berkeley Packet Filters format.

tshark: Another CLI packet sniffer software with full compatibility with its GUI counterpart, Wireshark. Supports 1,000 protocols and the list is growing. Useful to troubleshoot, analyze and store information on live packets.

ip: A versatile CLI networking tool which is part of iproute2 package. Used to check and modifying routing tables, network device state, and IP tunneling settings. Useful to view routing tables, add/remove static routes, configure network interfaces, and otherwise troubleshoot routing issues.

ifup/ifdown: Used to bring up or shut down a particular network interface. Often a preferred alternative to restarting the entire network service.

autossh: A program which creates an SSH session and automatically restarts the session should it disconnect. Often useful to create a persistent reverse SSH tunnel across restrictive corporate networks.

iperf: A network testing tool which measures maximum bi-directional throughput between a pair of hosts by injecting customizable TCP/UDP data streams in between.

iptables: A user-space CLI tool for configuring Linux kernel firewall. Provides means to create and modify rules for incoming, transit and outgoing packets within Linux kernel space.

nmap: A popular port scanning and network discovery tool used for security auditing purposes. Useful to find out which hosts are up and running on the local network, and what ports are open on a particular host.

TCP Wrappers: A host-based network ACL tool that can be used to filter incoming/outgoing reqeuests/replies. Often used alongside iptables as an additional layer of security.

Data management Tools

grep/egrep: Can be used to filter log content for a particular pattern or a regular expression. Variants include user-friendly ack and faster ag.

awk: A versatile text scanning and processing tool. Often used to extract certain columns or fields from text/log files, and feed the result to other tools.

sed: A text stream editor tool which can filter and transform (e.g., remove line/whitespace, substitute/convert a word, add numbering) text streams and pipeline the result to stdout/stderr or another tool.

Disk management tools.

fdisk: A disk partition editor tool. Used to view, create and modify disk partitions on hard drives and removable media.

sfdisk: A variant of fdisk which accesses or updates a partition table in a non-interactive fashion. Useful to automate disk partitioning as part of backup and recovery procedure.

parted: Another disk partition editor which can support disk larger than 2TB with GPT (GUID Partitioning Table). Gparted is a GTK+ GUI front-end of parted.

df: Used to check used/available storage and mount point of different partitions or file directories. A user-friendly variant dfc exists.

du: Used to view current disk usage associated with different files and directories (e.g., du -sh *).

mkfs: A disk formatting command used to build a filesystem on individual disk partitions. Filesystem-specific versions of mkfs exist for a number of filesystems including ext2, ext3, ext4, bfs, ntfs, vfat/fat.

fsck: A CLI tool used to check a filesystem for errors and repair where possible. Typically run automatically upon boot when necessary, but also invoked manually on demand once unmounting a partition.

mount: Used to map a physical disk partition, network share or remote storage to a local mount point. Any read/write in the mount point makes actual data being read/written in the corresponding actual storage.

mdadm: A CLI tool for managing software RAID devices on top of physical block devices. Can create, build, grow or monitor RAID array.

lvm: A suite of CLI tools for managing volume groups and physical/logical volumes, which allows one to create, resize, split and merge volumes on top of multiple physical disks with minimum downtime.
Log Processing Tools

tail: Used to monitor trailing part of a (growing) log file. Other variants include multitail (multi-window monitoring) and ztail (inotify support and regex filtering and coloring).

22. getfacl/setfacl: View and customize access control lists of files and directories, as extensions to traditional file permissions.

23. cryptsetup: Used to create and manage LUKS-encrypted disk partitions.

Backup Tools

logrotate: A CLI tool that can split, compress and mail old/large log files in a pre-defined interval. Useful for administration of busy servers which may produce a large volume of log files

rsync: A fast one-way incremental backup and mirroring tool. Often used to replicate a data repository to an offsite storage, optionally over a secure connection such as SSH or stunnel.

rdiff-backup: Another bandwidth-efficient, incremental backup tool. Maintains differential of two consecutive snapshots

Window management

screen: Used to split a single terminal into multiple persistent virtual terminals, which can also be made accessible to remote users, like teamviewer-like screen sharing.

tmux: Another terminal multiplexer tool which enables multiple persistent sessions, as well as horizontal/vertial splits of a terminal.

dvtm: windowed interface. Allows multiple windows to be used with a text terminal

Security assessment

lynis: A CLI-based vulnerability scanner tool. Can scan the entire Linux system, and report potential vulnerabilities along with possible solutions.

maldet: A malware scanner CLI tool which can detect and quarantine potentially malware-infected files. Can run as a background daemon for continuous monitoring.

rkhunter/chkrootkit: CLI tools which scan for potential rootkits, hidden backdoors and suspected exploits on a local system, and disable them.
Storage Tools

Clamav: MSWindows viros checker.

Getting help

cheat or man: A simple CLI tool which allows you to read cheat sheets of many common Linux commands, conveniently right at your fingertips. Pre-built cheat sheets are fully customizable.

apropos: Also known as man -k. Useful when you are searching man pages for descriptions or keywords.

Package Management Tools

apt: The de facto package manager for Debian based systems like Debian, Ubuntu, Backtrack or elementary OS. A life saver.

apt-fast: A supporting utility for apt-get, which can significantly improve apt-get’s download speed by using multiple concurrent connections.

apt-file: Used to find out which .deb package a specific file belongs to, or to show all files in a particular .deb package. Works on both installed and non-installed packages.

dpkg: A CLI utility to install a .deb package manually. Highly advised to use apt whenever possible.

yum: The de facto automatic package manager for Red Hat based systems like RHEL, CentOS or Fedora. Yet another life saver.

pacman:  The de facto automatic package manager for Arch linux. Yet another life saver.

rpm: Typically I use rpmyum something. Has some useful parameters like -q, -f, -l for querying, files and locations, respectively.
Hardware Tools

Diagnostic tools:

lspci: A command line tool which shows various information about installed PCI devices, such as model names, device drivers, capabilities, memory address, PCI bus address.

lshw: A command line tool which queries and displays detailed information of hardware configuration in various categories (e.g., processor, memory, motherboard, network, video, storage). Supports multiple output formats: html, xml, json, text.

inxi: A comprehensive hardware reporting tool which gives an overview of various hardware components such as CPU, graphics card, sound card, network card, temperature/fan sensors, etc.

iostat: A CLI tool which reports current CPU utilization, as well as device I/O utilization, where I/O utilization (e.g., block transfer rate, byte read/write rate) is reported on a per-device or per-partition basis.

duplicity: An encrypted incremental backup utility. Uses GnuPG to encrypt a backup, and transfers to a remote server over SSH.
Performance Monitoring Tools

top: A CLI-based process viewer program. Can monitor system load, process states, CPU and memory utilization. Variants include more user-friendly htop.

ps: Shows a snapshot of all running processes in the system. The output can be customized to show PID, PPID, user, load, memory, cumulative user/system time, start time, and more. Variants include pstree which shows processes in a tree hierarchy.

nethogs: A bandwidth monitoring tool which groups active network connections by processes, and reports per-process (upload/download) bandwidth consumption in real-time.

ngxtop: A web-server access log parser and monitoring tool whose interface is inspired by top command. It can report, in real time, a sorted list of web requests along with frequency, size, HTTP return code, IP address, etc.

vmstat: A simple CLI tool which shows various run-time system properties such as process count, free memory, paging status, CPU utilization, block I/O activities, interrupt/context switch statistics, and more.

iotop: An ncurses-based I/O monitoring tool which shows in real time disk I/O activities of all running processes in sorted order.

sysdig: A versatile and comprehensive open source tool for capturing and analyzing system behavior and server state in both real-time and offline modes.
Productivity Tools

——————————————————-

Last article I talked about using a dos disk to access some terminal software. Here is a disk that is allegedly pure linux to act as a terminal. It seemed to work on the old 486 laptop, though I did not check it out completely.

About:
PiTuX is a floppy based Linux distro that turns an old, low-RAM, machine in a very useful serial terminal running minicom. Think about your old laptop as a pure VT102.
Features:

  • PiTuX boots from a floppy and runs completely in ram so you can even have a diskless PC.
  • New: persistent configuration! Configure minicom as you need and if you want you can have config files stored and saved over reboots.
  • It works from 386, without math coprocessor, up and NEEDS ONLY 4 MB RAM.
  • It doesn’t have any kind of support for hard disks so it will not mess up data on them
  • Most 386 and 486 can run even without a fan so you can have a very silent serial terminal at the prize of a NULL MODEM cable.
  • 2.4 recent kernel, lightweight uClibc, and real minicom 2.1
  • full color, full ANSI mode!

Usage:
for administration of headless Linux/*BSD/VAX/etc, multiple servers/PC without the need of a KVM switch, installations via serial console, modem/router/firewall setup, monitoring equipment, embedded systems development, talk to your exotic hardware, when ssh is gone and you’re running for the ultimate login…
Why:
I’ve got an old IBM thinkpad 340, with only 4 MB RAM, and I thought to use it as a serial terminal, boot from floppy on a ramdisk and forget everything else.
There are other minicom-ready floppy distros but I can’t find one that fits in 4 MB RAM so I made my own. This is my little linux toy!
Download:
Floppy raw image:  ==> pitux-0.3.3.img <==
md5: c05b7657c7dfe7a70997fd2de880f1b4 pitux-0.3.3.img
sha1: 99deea4b38f618109d8994f5057da5720adb26e9 pitux-0.3.3.img
CD-ROM iso image:  ==> pitux-0.3.2.iso <==
md5: 81098e2934e173b260d40da7fe12f11f pitux-0.3.2.iso
sha1: 9efe8ca5602526ac21e82f26ccbfc589b6a58ca7 pitux-0.3.2.iso

Floppy creation, Linux:
insert a blank floppy in your PC, data on floppy will be lost!

cd /tmp
wget http://www.asashi.net/media/pitux-X.Y.Z.img
md5sum pitux-X.Y.Z.img
dd if=pitux-X.Y.Z.img of=/dev/fd0
(newer systems might use sudo dd if=pitux-X.Y.Z.img of=/dev/sdb Use fdisk to be sure)

wait…
when the prompt is back (hopefully without errors) put the floppy in the machine you would like to use and boot from floppy.
to test it with qemu:

qemu -fda pitux-X.Y.Z.img -boot a

or

qemu -cdrom pitux-X.Y.Z.iso -boot d

Persistent configuration:
a shiny new feature of my toy now let you drop into the floppy root three minirc.* files, during the boot sequence if they are found there they are used to overwrite the same files on the ramdisk so you can have you own minicom configuration. If the script does not find the second of them you are guided through an interactive configuration of the minicom instance on the 1st tty.
The files must have these names:
minirc.dfl: default config file [ttyS0,56700,8n1]
minirc.tty1: config file for the respawned minicom on tty1 [ttyS0,38400,8n1], good for a default login over serial line on a standard x86 linux machine
minirc.tty2: use it as you like just call minicom as:

minicom -c on tty2

You’ll find ready to use samples in /floppy/examples.
So you can mount the floppy (or loopmount the image) under any linux, write your minirc.* files with these names or you can configure minicom as you need from within PiTuX and then save your modified files with this command “persist”… oh ALT+F2 gives you a shell 🙂:

~ # persist
minirc.dfl saved on floppy
minirc.tty1 saved on floppy
minirc.tyy2 saved on floppy
sync floppy... ok
~ # _

The files are copied back on the floppy saved for the next reboot.
Bootable CD-ROM, Linux:
Here is a very small iso image that use isolinux:
pitux-0.3.2.iso
it still works with just 4 MB RAM, but given it’s on a really readonly media you can’t save any configuration.
So once you’re dropped into minicom configure it at your needs, save as default and restart minicom, your config will stay until reboot.
Also here ALT+F2 gives you a simple shell from where you can start another minicom with other settings:

minicom -c on tty2

 

 

——————————————————-

As much of a ‘nix advocate as I am, there are a few times when  for really old equipment, a dos boot disk just works. All you really need is a dos boot disk, a terminal program, usb to serial adapter, null modem cable. The biggest advantage of this is that you do not need a network to connect to the unit.

You can get dos from all boot disks and then use the dd command  to create a bootable disk. My computer did not have a floppy drive, so I found a usb floppy drive that was inexpensive. It is also great for making bios upgrade boot disks.

$ dd if=dosdisk.img of=/dev/sdb

For a terminal there are a variety to use. Started with our old dos terminal program to make sure things worked. Then we installed Hiterm on the boot floppy which takes little room.

$ sudo mkdir /mnt/flop
$ sudo mount /dev/sdb /mnt/flop.
$ sudo cp the hitermfiles  /mnt/flop/.
$ sync; sync
$ sudo umount /mnt/flop

 

There is a default configuration file you need to edit for the serial port parameters. but that is not such a big deal. We included several other files for testing and other projects.

$ ls
ABELPROG.BAT   DRVSPACE.BIN  GEN4800.CFG  lizzytrm.bas  PRG9600.CFG  TS.BAT
ABELPROG.CFG   GEN1200.CFG   GEN9600.CFG  MSDOS.SYS     qbasic.exe
ABELPROG.CFG~  GEN19200.CFG  HITERM.EXE   PRG19200.CFG  qbasic.hlp
COMMAND.COM    GEN300.CFG    IO.SYS       PRG4800.CFG   qbasic.ini

Use ABLEPROG.BAT to start the program.

You will also need to set up your serial connection depending on whether you are using the traditional serial port or the more modern usb to serial adapter.  Every distro is a little different on the setup. We used “Arch Working with the serial console – ArchWiki.html” as a guide. Was working in just a few minutes after a host reboot.

When logging in you may have to hit the return or enter key a few times for things to sync. Minimal login might be like this.

TestSystem Login: username
Password:
Last login: Sat Dec 6 09:32:54 on ttyUSB0
[username@TestSystem ~$ _

From there you can use the system just like a ethernet connection, but there will be no gui. it is almost like going retro.

If you do have ethernet connected you could use lynx to connect to the net. This is great if you need internet access  to fix and issue.

Google

Search Images Maps Play YouTube News Gmail Drive More »
Web History | Settings | Sign in

Google

_______________________________________________________
Google Search  I’m Feeling Lucky                          Advanced search
Language tools

Advertising Programs     Business Solutions     +Google     About
Google

© 2013 – Privacy & Terms

Enter a whereis query:
Arrow keys: Up and Down to move.  Right to follow a link; Left to go back.
H)elp O)ptions P)rint G)o M)ain screen Q)uit /=search [delete]=history list

You can even play games from the terminal such as ninvaders.

Having this terminal setup could also be used to rescuing other linux systems in the rare case you might need it. Last but not least the terminal mode is great for running all those page scraping scripts to get data off the internet, we have shown you.  It is not how powerful your machine is, but how you use it!

——————————————————-

If you go to a web page, you get to see all the pretty pictures and advertisements. What if you not only just want part of the page and to avoid all the advertisements or you do not have a gui based terminal? You can accomplish that with what is known as a page scrape. A page scrape extracts just the data we want without even having to look at a gui web page. What really happens we sort of print only the text from a page to the screen.

Take the following page:

$ firefox http://www.creators.com/lifestylefeatures/horoscopes/holiday-mathis-weekly.html

But all we really want is this part of the page.

Now consider we want to do everything from the command line, so that all you can use is text characters. No problem, but you have to use the mouse to highlight what we need and then paste it to the screen or to a file. The same page as text where we have scrolled down to where the data we want is.

$ lynx “http://www.creators.com/lifestylefeatures/horoscopes/holiday-mathis-weekly.html&#8221;

 

 

But then you would like to go one step further and have the computer visit the page and get and save the data for you. We can accomplish this with something as simple as using a shell script

logic:
#Get the page and dump it to the buffer.
lynx -width 1000 -dump “http://www.creators.com/lifestylefeatures/horoscopes/holiday-mathis-weekly.html&#8221;
# using the buffer, grep the page for some particular non-repeated text.
| grep $hsign
# Take that result and print it in a column so many characters wide
| fold -sw 60

So if we create a batch file the results might look like this:

$ ghpcl.sh
Enter your horoscope sign:
_
‘ `:–.–.
|  |  |_     Virgo-  The Virgin
|  |  | )
|  |  |/
(J

Today’s date: 12/05/14
Today’s horoscope for:
VIRGO (Aug. 23-Sept. 22). Instead
of looking to relationships to make
you happy, look to them to make you
conscious of what has been weighing
heavily inside you at an unconscious
level.

We have done this with many web pages. You have have to vary how you do it though. Just a little trial and error to get what you want. What is really neat is that you can combine several different page scrapes and make sort of your own newsletter. (Earlier articles have explained how to do that in detail.) Now you do not have to pour through many web pages just to get what you want. The computer will have done that for you.  Plus you can get a screen reader to put the words to speech!  Save the speech to an audio file for later listening from your music player.

$ lynx -width 1000 -dump “http://www.creators.com/lifestylefeatures/horoscopes/holiday-mathis-weekly.html&#8221; | grep “VIRGO” | fold -sw 60 > tts.txt
$ text2wave tts.txt -o tts.wav
$ play tts.wav

tts.wav:

File Size: 746k      Bit Rate: 256k
Encoding: Signed PCM
Channels: 1 @ 16-bit
Samplerate: 16000Hz
Replaygain: off
Duration: 00:00:23.30

In:100%  00:00:23.30 [00:00:00.00] Out:373k  [      |      ] Hd:2.4 Clip:0
Done.
$

Starting  your own podiobooks is going to the next level.

# Get today's horoscope
echo "--------------------------------------------"
# character width
cw=60
# If no sign entered, use virgo a default.
hsign=$1
if [ $# -lt "1" ]; 
then hsign="Virgo"
fi
# set the sign to upper case
hsign="`echo $hsign|tr '[a-z]' '[A-Z]'`"
#Print the  symbol text from an existing file
cat ~/signs/$hsign
# show the date
echo -n "Today's date: "
date +%D
# print out the data
echo "Today's horoscope for:"
lynx -width 1000 -dump
"http://www.creators.com/lifestylefeatures/horoscopes/holiday-mathis-weekly.html"
 | grep $hsign | fold -sw $cw
echo "--------------------------------------------"

Symbol files:

.-“-._.-“-._.-   Aquarius-  The Water Bearer
.-“-._.-“-._.-

.-.   .-.
(_  \ /  _)    Aries-  The Ram
|
|

.–.
/   _`.     Cancer-  The Crab
(_) ( )
‘.    /
`–‘
\      /_)    Capricorn-  The Goat
\    /`.
\  /   ;
\/ __.’

._____.
| |        Gemini-  The Twins
| |
_|_|_
‘     ‘

.–.
(    )       Leo-  The Lion
(_)  /
(_,

__
___.’  ‘.___   Libra-  The Balance
____________

`-.    .-‘   Pisces-  The Fishes
:  :
–:–:–
:  :
.-‘    `-.


.’:     Sagittarius-  The Archer
.’
`..’
.’`.

_
‘ `:–.–.
|  |  |      Scorpius-  The Scorpion
|  |  |
|  |  |  ..,
`—‘:

.     .
‘.___.’      Taurus-  The Bull
.’   `.
:       :
:       :
`.___.’

_
‘ `:–.–.
|  |  |_     Virgo-  The Virgin
|  |  | )
|  |  |/
(J

——————————————————-

Ever wondered what your computer is looking for. Some of these could be avenues for hackers to get into your machine. Actually this is looking for processes bound to specific ports.

Use the following command  to see wbat particular port your computer is listening for:

Terminal – Look for the process bound to a certain port:

sudo netstat -tulpn | grep :8080

 

Look for the process bound to a certain port
Or you could look at all the ports to 1000;
$ cat portscan.sh
for i in {1..1000}
do
echo $i
sudo netstat -tulpn | grep :$i
done
$./portscan.sh > portscan.file
You might see something  like this in the file.
628
629
630
631
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      2217/cupsd
tcp6       0      0 ::1:631                 :::*                    LISTEN      2217/cupsd
632
633
Cups is the unix print mechanism, Something you might want to keep and eye on once in a while or less.

——————————————————-

Another C program converted to work on Linux. This time with a bit different technique.

 

#include<stdio.h>

struct student

{

          int rollno;

          char name[20];

          char college[40];

          int score;

};

void main()

    {

          struct student s[20],temp;

          int i,j,n;

          clrscr();

          printf("\nEnter no. of Students : ");

          scanf("%d",&n);

          printf("\nEnter the rollno,name,college name,score ");

          for(i=0;i<n;i++)

          scanf("%d%s%s%d",&s[i].rollno,s[i].name,s[i].college,&s[i].score);

          for(i=0;i<=n-1;i++)

          {

            for(j=0;j<=n-1;j++)

            {

                if(s[j].score<s[j+1].score)

                {

                  temp=s[j];

                  s[j]=s[j+1];

                  s[j+1]=temp;

                }

            }

          }

          printf("\nThe Merit List is :\n");

          for(j=0;j<n;j++)

          printf("%d\t%s\t%s\t%d\n",s[j].rollno,s[j].name,s[j].college,s[j].score);

          getch();

        } 

Sort the Record of Student Merit Wise

My version:

#include<stdio.h>
#include <unistd.h>
#include <termios.h>

struct student
{
int rollno;
char name[20];
char college[40];
int score;
};

char getch(){
char buf=0;
struct termios old={0};
fflush(stdout);
if(tcgetattr(0, &old)<0)
perror(“tcsetattr()”);
old.c_lflag&=~ICANON;
old.c_lflag&=~ECHO;
old.c_cc[VMIN]=1;
old.c_cc[VTIME]=0;
if(tcsetattr(0, TCSANOW, &old)<0)
perror(“tcsetattr ICANON”);
if(read(0,&buf,1)<0)
perror(“read()”);
old.c_lflag|=ICANON;
old.c_lflag|=ECHO;
if(tcsetattr(0, TCSADRAIN, &old)<0)
perror (“tcsetattr ~ICANON”);
printf(“%c\n”,buf);
return buf;
}
void main()
{
struct student s[20],temp;
int i,j,n;
system(“clear”);
printf(“\nEnter no. of Students : “);
scanf(“%d”,&n);
printf(“\nEnter the rollno,name,college name,score “);
for(i=0;i<n;i++)
scanf(“%d%s%s%d”,&s[i].rollno,s[i].name,s[i].college,&s[i].score);
for(i=0;i<=n-1;i++)
{
for(j=0;j<=n-1;j++)
{
if(s[j].score<s[j+1].score)
{
temp=s[j];
s[j]=s[j+1];
s[j+1]=temp;
}
}
}
printf(“\nThe Merit List is :\n”);
for(j=1;j<=n;j++)
printf(“%d\t%s\t%s\t%d\n”,s[j].rollno,s[j].name,s[j].college,s[j].score);
getch();
}

——————————————————-

Mafalde pasta

SUNP0026

Good day.

Advertisements