Mail Archives: djgpp/1999/08/12/00:28:11
Hi difman,
difman wrote:
>
> sorry for reply to own post but the c code that caused the errors is
> attached to this message.
>
>#include <stdlib.h> // You should #include <stdio.h> also
>
>main(void) // main() should return an int
int main(void)
>{
> FILE *text;
> char filename[10]; // This should be bigger
char filename[127];
> char mytext[1000];
> int x = 0;
> int y = 0;
>
> printf("Enter name of file: ");
> gets(filename, 80); // incorrect see libc info
gets(filename);
>
> text = fopen(filename, "r"); // Should check if this fails
if (!text) {
printf("Error opening %s\n", filename);
return 1;
}
>
> while(mytext[x] != EOF) { // mytext[] is unitialized...
> x++;
> }
>
> while(y != x/2) {
> mytext[y] = fgetc(filename); // again mytext[] is unitialized
> putchar(mytext[y]);
> y++;
> }
>
> fclose(*text); // this is wrong
fclose(text);
>
> return 0;
>}
>
Okay, I assume you're trying to read in a file and print it to the
screen right?
Since I couldn't see how hacking your code into actually working would
benefit here is what you *could* have done :)
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *text_fp; // this is a file pointer not the contents of a file
char filename[128]; // space for a filename i.e. c:/test/file.txt
printf("Enter name of file: ");
gets(filename); // get the users input
text_fp = fopen (filename, "r");
if (!text_fp) // check for failed fopen
{
printf ("Failed to open %s\n", filename);
return (EXIT_FAILURE);
}
// This reads each char and prints them until EOF
while ( putchar(fgetc(text_fp)) != EOF)
;
fclose (text_fp);
return (EXIT_SUCCESS);
}
But also, this isn't the best or only way to do it.
- Raw text -