i need a sample program for handling text files using c language.. i don't know the syntaxes.. please help me and provide some comments on the source code so that i'll be on track..

Things that i need:
1) How to locate the text file
2) How to input values in that text file
3) How to read the texts in the text file
4) What are the things that i need to consider in creating the program


Thanks a lot...

Recommended Answers

All 24 Replies

>How to locate the text file
What do you mean by this? Do you mean "open" the file when you already know the name? Or are you searching for a text file on your hard drive?

>How to input values in that text file
>How to read the texts in the text file

http://www.cprogramming.com/tutorial/cfileio.html

>What are the things that i need to consider in creating the program

Make sure you don't use feof() to check if you're at the end of the file. See this explanation:
http://www.gidnetwork.com/b-58.html

yes.. to locate a textfile on my hard drive so that i could read the text file and display its contents.. thanks for the links..

the very basic basics of C file handling.

if ((fp = fopen(filename,"r"))==NULL) 
{
	printf("cannot open file `%s`\n",filename);
	exit (1);
}

while (fgets(buf,80,fp))   // this assumes text lines are less than 80 chars!
{
	if (strstr(buf,"waldo") != NULL) {
		printf("found him!");
		waldo++;	
	}
	printf("I found waldo on %d lines.\n",waldo);
}

fclose (fp);

this will get you started.

remember you always need to #include <fileio.h>

the very basic basics of C file handling.

remember you always need to #include <fileio.h>

I guess you meant stdio.h .

I guess you meant stdio.h .

oops, yeah. thanks

and i also meant to put the last "printf" statement *AFTER* the close of the while() block.

:P

I guess you meant stdio.h .

oops, yeah. thanks

and i also meant to put the last "printf" statement *AFTER* the close of the while() block.

:P

This is why we recommend you test code you post. It generally doesn't help the poster if you give bad advice --- they rarely know it's bad.

well I am new here .... but I didn't think the purpose of this site is to supply completely error-free and 100% syntactically-correct source code for people to cut-and-paste. thats what homework services do. im just giving ideas and a framework of code fragments on how to solve the problem.

anyhow, there's got to be some amount of effort and initiative to solve problems here. amirite?

well I am new here ....

So? Isn't it obvious even to someone new you don't want to answer a question with invalid advice? :icon_wink:

but I didn't think the purpose of this site is to supply completely error-free and 100% syntactically-correct source code for people to cut-and-paste. thats what homework services do. im just giving ideas and a framework of code fragments on how to solve the problem.

anyhow, there's got to be some amount of effort and initiative to solve problems here. amirite?

You are absolutely correct. But if the small snippets of code you post are filled with errors in syntax and/or logic, how have you really helped someone? They get confused, then post "I don't understand why your advice didn't work!", then you have to apologize and correct your post. They've lost a day because of an invalid code snippet. That's what I'm saying. So try to verify before you post, that's all.

And of course errors slip in. But fewer will by testing/proofreading. :icon_wink:

"filled with errors" ??

step off my grill, dog. the code snippet -- as it is written -- *works* and it is entirely suitable for someone wanting code handed to them.

now tell me, do you always engage in such tendentious pedantry on trivial matters, or do you reserve this unappealing behavior only for the new people?

:roll:

now tell me, do you always engage in such tendentious pedantry on trivial matters, or do you reserve this unappealing behavior only for the new people?

Are you saying you never read the fraternity initiation test post?
So far the judges are not impressed.
You better be ready for the "code optimization" test. That's a toughy!.

So far the judges are not impressed.

what? are you kidding?

i even had to go look up "tendentious", dammit.

:P

what? are you kidding?

i even had to go look up "tendentious", dammit.

:P

Yes, I was kidding. Keep posting, and don't take anything personal.
We love battles of egos over here. Make us proud. ;)

hey guys.. thanks anyway with the source code especially to jephthah.. it helped me create a code based on my understanding and reading various posts.. hope you'd all still be interested in helping newbies like me.. i want to share the code that i have come up.. criticize my program and tell me some tips or tell me about any part of the code that is, what i can say "unheathy" to use.. thanks..

/* This is my TEST.C program*/
#include<stdio.h>
#include<conio.h>
#include<dir.h>
#include<dos.h>
#include<stdlib.h>
#include<string.h>

char retry;
int x;

create_and_read()
{
	FILE *pt;
	char name[80], line[80], letter;
	chdir("c:\\tc\\where");
	pt = fopen("myVenus.txt", "w");
	printf("Enter your name: ");
	gets(name);
	for(x = 0; x < strlen(name); x++)
	{
		if(name[x] == ' ')
			fprintf(pt, "%c", '\n');
		else
			fprintf(pt, "%c", name[x]);
	}
	fclose(pt);

                // For reading the text that was created by the code above and displaying it 
	pt = fopen("myVenus.txt", "r");
	if(!pt)
		return 1;
	while(fgets(line, 80, pt) != NULL)
		printf("%s", line);
	fclose(pt);
}

main()
{
	clrscr();
	create_and_read();
	repeat_process:
	printf("\nDo you wish to retry?[y/n] ");
	retry = getche();
	switch(retry){
		case 'y':
			clrscr();
			main();
			break;
		case 'n':
			clrscr();
			printf("Goodbye!");
			getch();
			break;
		default:
			goto repeat_process;
			break;
	}
}

I had to admit, it's not that good.. any advice??? thanks...

Yes, I was kidding. Keep posting, and don't take anything personal.

i know, i will, i dont

:)

now, back to the OP

"filled with errors" ??

step off my grill, dog. the code snippet -- as it is written -- *works* and it is entirely suitable for someone wanting code handed to them.

now tell me, do you always engage in such tendentious pedantry on trivial matters, or do you reserve this unappealing behavior only for the new people?

:roll:

No, I engage in supercilious bravura with any personage that imparts tenebrous erudition.

If someone attempts to correct you, don't get defensive. Think about what they said. They may have more experience than you and might be able to teach you something. :icon_wink:

After 30 years as a professional in computers, I still learn stuff here.


And as Aia said,

... don't take anything personal.
We love battles of egos over here. Make us proud. ;)

#include<conio.h>

Don't use this header or the functions it provides. They're old, outdated, non-standard, and non-portable. To pause the program at the end of execution, use getchar() .

#include<dir.h>
#include<dos.h>

You shouldn't need these.

char retry;
int x;

Ideally, you shouldn't use globals. You have no need for them; declare them in the functions that they're needed.

chdir("c:\\tc\\where");
pt = fopen("myVenus.txt", "w");

Why do you change the directory? Just specify the full path in fopen() . Also, if memory serves me right, you can use forward slashes instead of backwards ones. This also makes your program more portable.

gets(name);

That's a big no-no. gets() has no bounds-checking, so if the user enters more than your variable can hold, down she goes! Use scanf() or use fgets() to read from stdin instead.

for(x = 0; x < strlen(name); x++)
{
   if(name[x] == ' ')
      fprintf(pt, "%c", '\n');
   else
      fprintf(pt, "%c", name[x]);
}

Is there any reason why you're printing each character individually, as opposed to outputting the entire string at once?

retry = getche();

This function is from the outdated conio.h as mentioned earlier. Use getchar() instead.

never, ever, use GOTO

a horrible horrible thing they did, by allowing that command in the language.

use a while() loop instead.

sir joeprogrammer i have questions.. i'm already done with some of your suggestions and they worked.. but i have troubles implementing the scanf or fgets instead of the gets..

in scanf("%s", &name); is this the right way of using the scanf? when i display the contents of the text file, if i input "This is", "This" is the only word displayed..

how to use the fgets?

how to use the getchar()?? thanks sir

scanf is not free of its own problems so I would recommend not using it.
the proper syntax would be scanf( "%s", name );. No &.
fgets() is the one you should invest time learning.
proper syntax for it could be:

fgets( name, sizeof name, stdin );

the use of getchar() could be like this:

int ch; /* declaring an int */

ch = getchar(); /* reading a character from stream and assigning it to ch */

Be aware, though, that if you use fgets(), you're going to have to trim a trailing newline from the string that results from the user pressing 'enter'.

Also, another thing I forgot to mention was getchar(). It works fine in the manner that Aia described, however, you might run into problems with it because of characters still left in the input buffer. Input functions such as fgets() grab an entire line, so they don't screw anything up. However, getchar() only grabs one character. That means there's still a newline sitting in the input buffer (from the user hitting 'enter'). Additionally, if they enter more than one character, these also will be sitting in the input buffer.

So how do you get rid of all this crap? Here's how you clear the input buffer:

int ch;
while ( ( ch = getchar() ) != '\n' && ch != EOF );

Use the above code if you find that your program seems to "miss" calls to getchar().

Without any desire to be picky, I would like to point out there's the need for a semicolon after that while loop, either right in the same line or below with indentation to show is not a mistake.

int ch;
while ( ( ch = getchar() ) != '\n' && ch != EOF )
    ; /* work is done in the loop */

Fixed.

commented: The difference between the amateur and the pro is the pro knows how to fix his errors +7

thanks to all.. your contributions are really great and effective.. hope someday i'll become an expert like you fellahs!..

>hope someday i'll become an expert like you fellahs!..
You will, with practice and dedication.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.