-
How Do I "c"?
K im pretty fluent with python but have recently switched too "C" and found it far more complicated =( i was wondering if anybody could help me with opening a file named "program" ?? Im on linux, and i wanna open a file in my home directory and get the letters fpdirectory. . So far i have this
#include <stdlib.h>
#include <stdio.h>
main()
{
FILE *program;
do {
char ch;
ch = getc(fp);
}
while(ch!=EOF);
}
can you tell me what im doing wrong plz??? thanks a ton
Sorry i forgot to include something
FILE *program;
fopen(program);
do {
THATS how it really is i accidently typed it in wrong
-
Hi WhiteDwarf18, not 100% certain what you are trying to do, but it looks to me like you are trying to read the contents of a file to STDOUT. Here is a simple (crude is a better word :) ) example of reading from a file with fopen()
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFSIZE 128
int main( void )
{
FILE *fp;
char ch, buf[BUFSIZE], filename[128];
// What file do you want to read?
printf( "Enter the name of the file you want to read: " );
fgets( filename, 128, stdin );
filename[strlen( filename ) -1 ] = 0;
// Open the file for reading
if (( fp = fopen( filename, "r" )) == NULL )
{
fprintf( stderr, "Error opening file.\n" );
exit( 1 );
}
// While the end of the file has not been reached, read a line and display it
do
{
fgets( buf, BUFSIZE, fp );
printf( "%s", buf );
} while( !feof(fp) );
printf( "\n" );
fclose( fp );
return 0;
}
// Alternatively, we could have done a while loop similar to the one
// in your post which might look something like this.
//
// do
// {
// printf( "%c", ch );
// } while(( ch = fgetc( fp ) != EOF );
Hope that helps