Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Simple File Manipulation 4

Status
Not open for further replies.

houksyndrome

Technical User
Jun 27, 2001
7
US
I am a beginner programmer and have a rudimentary knowledge of C and no knowledge of the other languages. I need to write a program that will first ask the user to type in the name of the file that he wants to open, then opens that file and displays the contents on the screen. It will be the foundation for a more complex program. I would be extremely grateful for any help doing this. Please include program code because the concept involved seems pretty straight forward, I just can't figure out the syntax to use. Thanks a lot!

Andrew

 
Please post your best attempt and we'll be happy to help you. When you ask for help in this manner, many people will interpret this as a homework assignment that you're trying to get the forum to do for you.

Whether this is your intent or not, this site is more about helping people with problems than just supplying the code according to some specs that the poster lays out (however trivial the program).
Russ
bobbitts@hotmail.com
 
I think something like this might work

char filename[128];

cout<<&quot;Enter the file name: &quot;;
cin>>filename;

system(filename);

I belive the system call with filename will use the default program to open the file. This is just a guess though. It did not work with .doc files for me but txt files opened fine.

if not, i think you will need to use ifstream to input the file.

matt
 
I had tried to write something like this, but I keep getting segmentation faults. This program might be way off of what I want to do, but I am a beginner.

#include <stdio.h>

main()
{
char name[100];
char cont[100];
FILE *thefile;

(void)printf(&quot;What file? &quot;);
(void)fgets(name, sizeof(name), stdin)
name[strlen(name)-1] = ' ';

thefile = fopen(name, &quot;r&quot;);
(void)fgets(cont, sizeof(cont), thefile);

(void)printf(&quot;%s&quot;, cont);
fclose(thefile);
return (0);
}
 
>#include <stdio.h>

#include <string.h> /* for strlen() */

>main()

This is perfectly legal, but the new C standard disallows implicit int return from main().

>{
> char name[100];

For file name lengths, there's a macro called FILENAME_MAX found in <stdio.h> that is the longest file name that can be handled by the environment. This would be a better choice than the arbitrary 100.

> char cont[100];
> FILE *thefile;

> (void)printf(&quot;What file? &quot;);

Add an fflush(stdout); here to ensure that the user sees the prompt before they can enter input. It would also be helpful to inform the user of how long the filename can be.

> (void)fgets(name, sizeof(name), stdin)

You're missing a semi-colon at the end of this line.

You should check the return value of fgets(). It returns NULL on failure, which doesn't happen very often when reading from stdin, but still certainly worth checking.

> name[strlen(name)-1] = ' ';

It's also worthwhile to check that there actually is a new line that was left at the end of the string by fgets(). In cases where the user enters more than sizeof name - 1 characters, fgets() doesn't retain the newline character. So, if this happened, you'll be deleting the last character the user entered.

It's also more typical to set this character to the NUL terminator '\0' which effectively ends the string. I don't think you want to append a space character to the end of your file name.

> thefile = fopen(name, &quot;r&quot;);

You should definitely check to make sure fopen() didn't return NULL, which happens in cases where the file doesn't exist and for other reasons.

> (void)fgets(cont, sizeof(cont), thefile);

Probably what's causing your seg fault is that the name of the file you gave the program doesn't exist and fopen() is returning a NULL pointer, invoking undefined behavior on this line when you pass a NULL pointer in the 3rd argument which fgets() is obliged to assume is not NULL. The fact that you're setting the newline character retained by fgets() to a space character might be significant.

Also, you said above that you wanted to print out contents of the file, I'm assuming this means the whole file. Maybe this is where you're stuck, see below.

> (void)printf(&quot;%s&quot;, cont);

It's usually a good idea to add a newline character so that the command prompt doesn't end up on the same line as the last line of output.

> fclose(thefile);
> return (0);
>}

I know I made a lot of comments on your program but don't take it the wrong way, your code really isn't so bad. You're actually avoiding many common pitfalls :)

Another overall note: drop all the casts to void. This ultimately is just a style point because there's nothing technically wrong with doing this, but I can assure you, you'll drive yourself batty if you take this idea to its logical conclusion in your programs.

Personally, I sometimes do this when:

1. I ignore the return value of a function that I almost always don't ignore the return value of.

2. To silence compiler warnings for unused variables in callback functions.

There are some versions of lint that will generate diagnostics telling you that you're ignoring the return value of a function, thus all the casts to void to shut up lint. But, I would suggest turning down the level of strictness on lint rather than littering your code with (void).

Try this (I hope I haven't made any serious mistakes ;)

#include <stdio.h>
#include <stdlib.h> /* for EXIT_FAILURE */
#include <string.h>

int main()
{
char name[FILENAME_MAX+1];
char cont[100];
FILE *thefile;

printf(&quot;What file? (Max %d characters) &quot;,FILENAME_MAX);
fflush(stdout);

if (!fgets(name, sizeof(name), stdin)) {
/* fgets() totally flopped */
perror(&quot;fgets() error&quot;);
return EXIT_FAILURE;
} else {
/* Locate the newline character, if any */
char *tmp=strchr(name,'\n');
if (tmp) {
*tmp=0; /* Remove the newline */
} else {
fprintf(stderr,&quot;File name was truncated!\n&quot;);
}
}

thefile = fopen(name, &quot;r&quot;);
if (!thefile) {
perror(&quot;File open failure&quot;);
return EXIT_FAILURE;
} else {
char *tmp;
/* Loop through each line of the file */
while (fgets(cont,sizeof cont,thefile)) {
tmp=strchr(cont,'\n');
if (tmp) {
/* The line could fit in cont, just print it */
printf(&quot;%s&quot;,cont);
} else {
/* The line was truncated, report the error
* and print the line, adding our own new line
* to the output
*/
fprintf(stderr,&quot;line %s was truncated\n&quot;,cont);
printf(&quot;%s\n&quot;,cont);
}
}
fclose(thefile);
}
return 0;
}
Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top