Help in C

Any other programming language that is not covered in the Web Scripting category.

Help in C

Postby pugrit on Tue Dec 27, 2005 7:43 pm

guys, can you help me with files? like sample codes? before christmas vacation our professor gave us assignments (20 problems) to be submitted when the break is over. so far iv answered the rest but some i havent especially regarding on FILEs. i was kind absent when this was discussed so i find it hard just plain reading tutorials from the net.

so far my probels are:

how can i open an existing textfile and display it on the screen

how can i copy an entire file to another file. (filename.txt to filename2.txt)

and lastly how can i do a search on an existing file? example, in the textfile i saved names and number and i want to look for one entry and if that entry is found it will dispaly in the screen.

all this using (turbo C) C FILES.

i hate this holiday assignemnets. anyways, if anyone can help me, id be really grateful. sorry to bother you up guys..
pugrit
Phoenix Veteran
Phoenix Veteran
 
Posts: 293
Joined: Thu Mar 10, 2005 1:06 pm
Location: /home/pugrit

Postby chinnu on Wed Dec 28, 2005 5:47 pm

for all the answers supply the parameters as arguments to main function

answer 1:
int main(int argc, char *argv[])
{
FILE *fp;
int c;
if(argc != 2){
printf("Unmatched no. of parameters");
exit(1);
}
if((fp=fopen(*(argv+1),"r"))==NULL){
printf("file cannot be opened");
exit(1);
}
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
return 0;
}

answer 2:
int main(int argc, char *argv[])
{

void filecopy(FILE *,FILE *);
int c;
FILE *fp,*fp1;
if(argc != 3){
printf("Unmatched no. of parameters");
return 0;
}
if((fp=fopen(*(argv+1),"r"))==NULL){
printf("file cannot be opened");
exit(1);
}
if((fp1=fopen(*(argv+2),"w"))==NULL){
printf("file cannot be opened");
exit(1);
}
filecopy(fp,fp1);
fclose(fp);
fclose(fp1);
if((fp1=fopen("input1.txt","r"))==NULL){
printf("file cannot be opened");
exit(1);
}
while((c=fgetc(fp1))!= EOF){
printf("%c",c);
}
return 0;
}

void filecopy(FILE *fp1,FILE *fp2)
{
int c;
while((c=fgetc(fp1))!= EOF)
{
putc(c,fp2);
}
}


answer 3:
int main(int argc, char *argv[])
{
FILE *fp;
char msg[100];
if(argc != 3)
{
printf("Unmatched no. of parameters");
exit(1);
}
if((fp=fopen(*(argv+1),"r")) == NULL)
{
printf("file cannot be opened");
exit(1);
}
while((fgets(msg,100,fp))!=NULL)
{
if(strstr(msg,*(argv+2))!= NULL)
{
printf("String found\n%s",msg);
}
}
fclose(fp);
return 0;
}

bye
chinnu
!@#$%^&*()~)(*&^%$#@!~

karthik. k
chinnu
Newbie
Newbie
 
Posts: 3
Joined: Tue Dec 06, 2005 7:23 am

Postby pugrit on Thu Dec 29, 2005 8:04 pm

ok thanks, i will it out.
pugrit
Phoenix Veteran
Phoenix Veteran
 
Posts: 293
Joined: Thu Mar 10, 2005 1:06 pm
Location: /home/pugrit


Return to Programming

Who is online

Users browsing this forum: No registered users and 1 guest

cron