Sunteți pe pagina 1din 2

15 May 2015

Programming Fundamentals
Assignment 3
Write a program in C that:

Opens a text file for reading


Randomly reads a name from a the file
Prints it on the screen.
Says "Press any key to continue, q to quit"
Program will continue to print random names from the file till user presses q or Q.

Please note the file is a plain text file with one name per line.
Please note you will be using random access filing only to read one name (don't read the whole file)
Hint: You can use fix length names with empty spaces at the end to make random access work.
Sample File:
Muhammad Shehryar Khan
Muhammad Asim Iqbal
Shahab Shahid
Bilal Zulifqar
Muhammad Adeel Hussain
Erish Nadeem
Muhammad Usman
Awab Aqib
Mobeen Ahmad
Usama Sadiq

15 May 2015

Solution
#include
#include
#include
#include

<stdio.h>
<conio.h>
<stdlib.h>
<time.h>

int main(void)
{
char choice;
srand(time(NULL));
FILE *fp=fopen("Input.txt","r");
const int namelength = 24;
char input[23];
int a=0;
while (true)
{
a=rand()%11;
fseek(fp,a*namelength,SEEK_SET);
fscanf(fp,"%22[^\n]s",input);
printf("%s\n",input);
printf("Press any key to continue or q,Q to exit: ");
choice=getch();
if (choice=='q' || choice=='Q')
{
break;
}
}
fclose(fp);
}

S-ar putea să vă placă și