# How to read in a file in C.

## Recommended Posts

JavaMava    190
I have an assignment that requires me to read in a .txt file and then perform calculations on the data. My professor has posted code that technically does it, however he's filled in a lot of other stuff that's good habit, but is complicating me being able to figure out what exactly is going on. Here it is.
/* files1.c */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char text[256] = "";
int test = 0 ;

/********* STEP 1 - define the files *****/
FILE* in;
FILE* out;

/********* STEP 2 - open the files for processing *****/
in   = fopen("input.txt", "r");  /* input file - read mode */
if (in == NULL)
{
printf("input file not opened");
exit(1);
}

out  = fopen("output.txt", "w");  /* output file - output mode */
if (out == NULL)
{
printf("output file not opened");
exit(1);
}

/********* STEP 3 - process the files *****/
fgets(text, sizeof(text) - 1 , in);
while (! feof(in))
{
printf("I just read %d bytes : %s", strlen(text), text);
fprintf(out, "%s\n", text);
fgets(text, sizeof(text) - 1 , in);
}

/********* STEP 4 - close the files *****/
fclose(out);
fclose(in);

return 0;
}

My issue with this is when I run it, the app window pops up and goes away (even if I add a scanf at the bottom) then the program creates a text document called output in which it writes it output to instead of on the screen. It also makes and .exe file which I can click and run and it will keep the application window up for me to look at. This is very confusing as usually I can run it straight from blood shed. My question for you lovely people is; would it be possible for you to post some sample code for the quickest/simplest way to read in a file and print it out on screen in C? Perhaps with that I could figure out how it works exactly and do the rest of the assignment. Thanks for your time. PS - yes I did make an input.txt for the program to use and it uses it.

##### Share on other sites
Jan-Lieuwe    206
change 'fprintf(out, ...)' to 'fprintf(stdout, ...)'. If this is a console application, the output will go the console instead.

So 'fprintf(stdout, ...)' will basically behave the same as a regular 'printf'.

(Or am I missing your point? :)

You can add something like:

system("pause");

...at the end of your program if the window disappears after execution. You can also just run the program from a console window ([windows key]+[R], cmd, [enter]) or put a breakpoint somewhere and run it through the debugger.

##### Share on other sites
longjumper    127
int main()
{
FILE* f = fopen("file.txt", "rt");
fseek(f, 0, SEEK_END);

long fileLength = ftell(f);
fseek(f, 0, SEEK_SET);

char* bytes = (char*)malloc(sizeof(char) * fileLength);
fread(bytes, sizeof(char), fileLength, f);

printf("%s\n", bytes);
free(bytes);
return 0;
}

##### Share on other sites
JavaMava    190
hmm still getting the same thing, heres what I got

/* files1.c */#include <stdio.h>#include <stdlib.h>#include <string.h>int main(){  char text[256] = "";  int test = 0 ;  /********* STEP 1 - define the files *****/  FILE* in;  FILE* out;    /********* STEP 2 - open the files for processing *****/  in   = fopen("input.txt", "r");  /* input file - read mode */  if (in == NULL)  {    printf("input file not opened");    exit(1);  }  out  = fopen("output.txt", "w");  /* output file - output mode */  if (out == NULL)  {    printf("output file not opened");    exit(1);  }    /********* STEP 3 - process the files *****/  fgets(text, sizeof(text) - 1 , in);  while (! feof(in))  {    printf("I just read %d bytes : %s", strlen(text), text);    fprintf(stdout, "%s\n", text);    fgets(text, sizeof(text) - 1 , in);  }  /********* STEP 4 - close the files *****/  fclose(out);  fclose(in);  scanf ("%d", &test);  return 0;}

##### Share on other sites
Jan-Lieuwe    206
Quote:
 Original post by longjumperint main(){ FILE* f = fopen("file.txt", "rt"); fseek(f, 0, SEEK_END); long fileLength = ftell(f); fseek(f, 0, SEEK_SET); char* bytes = (char*)malloc(sizeof(char) * fileLength); fread(bytes, sizeof(char), fileLength, f); printf("%s\n", bytes); free(bytes); return 0;}

If all you (OP) really want is code that reads an ASCII file and outputs it to the console, then longjumper's code is what you're looking for. Just keep in mind that it's not written in C ;)

Hint: in C variables can only be declared at the beginning of a scope.

##### Share on other sites
JavaMava    190
Quote:
 Original post by Jan-Lieuwechange 'fprintf(out, ...)' to 'fprintf(stdout, ...)'. If this is a console application, the output will go the console instead.So 'fprintf(stdout, ...)' will basically behave the same as a regular 'printf'.(Or am I missing your point? :)You can add something like:system("pause");...at the end of your program if the window disappears after execution. You can also just run the program from a console window ([windows key]+[R], cmd, [enter]) or put a breakpoint somewhere and run it through the debugger.

Yes the window disappears after execution, even with your solutions above. I can run it through the cmd prompt it also creates a .exe of the program in the folder the project it's saved in that I can run it from. My issue is, why is it disappearing as my other program never have. Why is it making an .exe as my other programs never have.

I think theres code in there I don't quite understand thats doing this and thats what makes me uneasy.

Quote:
Original post by Jan-Lieuwe
Quote:
 Original post by longjumperint main(){ FILE* f = fopen("file.txt", "rt"); fseek(f, 0, SEEK_END); long fileLength = ftell(f); fseek(f, 0, SEEK_SET); char* bytes = (char*)malloc(sizeof(char) * fileLength); fread(bytes, sizeof(char), fileLength, f); printf("%s\n", bytes); free(bytes); return 0;}

If all you (OP) really want is code that reads an ASCII file and outputs it to the console, then longjumper's code is what you're looking for. Just keep in mind that it's not written in C ;)

Hint: in C variables can only be declared at the beginning of a scope.

Ya, I'm still a beginner programmer so the fact that this code had half a dozen errors when all I did was copy and paste... it scared me away form it.

##### Share on other sites
Jan-Lieuwe    206
Quote:
 Original post by JavaMavahmm still getting the same thing, heres what I got*** Source Snippet Removed ***

What do you mean with 'same thing'? The window disappears?

##### Share on other sites
Jan-Lieuwe    206
Quote:
Original post by JavaMava
Quote:
 Original post by Jan-Lieuwechange 'fprintf(out, ...)' to 'fprintf(stdout, ...)'. If this is a console application, the output will go the console instead.So 'fprintf(stdout, ...)' will basically behave the same as a regular 'printf'.(Or am I missing your point? :)You can add something like:system("pause");...at the end of your program if the window disappears after execution. You can also just run the program from a console window ([windows key]+[R], cmd, [enter]) or put a breakpoint somewhere and run it through the debugger.

Yes the window disappears after execution, even with your solutions above. I can run it through the cmd prompt it also creates a .exe of the program in the folder the project it's saved in that I can run it from. My issue is, why is it disappearing as my other program never have. Why is it making an .exe as my other programs never have.

I think theres code in there I don't quite understand thats doing this and thats what makes me uneasy.

Quote:
Original post by Jan-Lieuwe
Quote:
 Original post by longjumperint main(){ FILE* f = fopen("file.txt", "rt"); fseek(f, 0, SEEK_END); long fileLength = ftell(f); fseek(f, 0, SEEK_SET); char* bytes = (char*)malloc(sizeof(char) * fileLength); fread(bytes, sizeof(char), fileLength, f); printf("%s\n", bytes); free(bytes); return 0;}

If all you (OP) really want is code that reads an ASCII file and outputs it to the console, then longjumper's code is what you're looking for. Just keep in mind that it's not written in C ;)

Hint: in C variables can only be declared at the beginning of a scope.

Ya, I'm still a beginner programmer so the fact that this code had half a dozen errors when all I did was copy and paste... it scared me away form it.

Your windows would only disappear if the CPU executes one of those 'exit(1)' statements. Those are executed when your program doesn't find 'input.txt' or when it cannot generate 'output.txt' (the latter being unlikely). Is 'input.txt' in the same folder as your executable?

All C / C++ projects would generate an .exe file, btw. So I don't understand what you're referring to when you say: "Why is it making an .exe as my other programs never have." - unless your previous projects were written using a different language.

##### Share on other sites
JavaMava    190
Quote:
Original post by Jan-Lieuwe
Quote:
 Original post by JavaMavahmm still getting the same thing, heres what I got*** Source Snippet Removed ***

What do you mean with 'same thing'? The window disappears?

yes

##### Share on other sites
JavaMava    190
Quote:
 Original post by Jan-LieuweYour windows would only disappear if the CPU executes one of those 'exit(1)' statements. Those are executed when your program doesn't find 'input.txt' or when it cannot generate 'output.txt' (the latter being unlikely). Is 'input.txt' in the same folder as your executable?All C / C++ projects would generate an .exe file, btw. So I don't understand what you're referring to when you say: "Why is it making an .exe as my other programs never have." - unless your previous projects were written using a different language.

I guess it muse be one of the exit commands, I'll go try that. It does find input.txt though as when I run the .exe it takes the text inside the input.txt and displays it on screen. Yes input.txt is in the same folder.

As for the confusion around generating .exe files, that must be my own mistake. We use a text based network, phobos, in my college so I never really see all my files unless I'm specifically looking for them. I guess when I'm at my home PC I just never noticed the .exe.

EDIT - just removed the exits, and the windows stays up. It displays the error message that it can't find input.txt so I guess I was some how mistaken there...

I just tried the .exe again and it finds the input.txt

##### Share on other sites
Jan-Lieuwe    206
Quote:
Original post by JavaMava
Quote:
 Original post by Jan-LieuweYour windows would only disappear if the CPU executes one of those 'exit(1)' statements. Those are executed when your program doesn't find 'input.txt' or when it cannot generate 'output.txt' (the latter being unlikely). Is 'input.txt' in the same folder as your executable?All C / C++ projects would generate an .exe file, btw. So I don't understand what you're referring to when you say: "Why is it making an .exe as my other programs never have." - unless your previous projects were written using a different language.

I guess it muse be one of the exit commands, I'll go try that. It does find input.txt though as when I run the .exe it takes the text inside the input.txt and displays it on screen. Yes input.txt is in the same folder.

As for the confusion around generating .exe files, that must be my own mistake. We use a text based network, phobos, in my college so I never really see all my files unless I'm specifically looking for them. I guess when I'm at my home PC I just never noticed the .exe.

Ah, what system are you working on? I was sort of assuming you were creating a console application using Visual C++ on a Windows machine. system("pause"); isn't very portable!

If you see the output, then input.txt definitely can be found and the output.txt file can be generated. So it's not executing one of the exit calls then.

Another thing I used to use:

/* include this */#include <conio.h>/* use this to wait for a key */while (!kbhit()){   /* waiting for key... */}

(but I don't think that's part of the ANSI C standard either... getch() is another option)

Edit: just saw your edit. Glad you figured it out!

##### Share on other sites
JavaMava    190
Quote:
Original post by Jan-Lieuwe
Quote:
Original post by JavaMava
Quote:
 Original post by Jan-LieuweYour windows would only disappear if the CPU executes one of those 'exit(1)' statements. Those are executed when your program doesn't find 'input.txt' or when it cannot generate 'output.txt' (the latter being unlikely). Is 'input.txt' in the same folder as your executable?All C / C++ projects would generate an .exe file, btw. So I don't understand what you're referring to when you say: "Why is it making an .exe as my other programs never have." - unless your previous projects were written using a different language.

I guess it muse be one of the exit commands, I'll go try that. It does find input.txt though as when I run the .exe it takes the text inside the input.txt and displays it on screen. Yes input.txt is in the same folder.

As for the confusion around generating .exe files, that must be my own mistake. We use a text based network, phobos, in my college so I never really see all my files unless I'm specifically looking for them. I guess when I'm at my home PC I just never noticed the .exe.

Ah, what system are you working on? I was sort of assuming you were creating a console application using Visual C++ on a Windows machine. system("pause"); isn't very portable!

If you see the output, then input.txt definitely can be found and the output.txt file can be generated. So it's not executing one of the exit calls then.

Another thing I used to use:

/* include this */
#include <conio.h>

/* use this to wait for a key */
while (!kbhit())
{
/* waiting for key... */
}

(but I don't think that's part of the ANSI C standard either... getch() is another option)

my issue right now is if I run the .exe it works. If I run it from blood shed it displays "Input file not opened". I removed the exit's. So that explains why it wasn't staying up, however what would cause the .exe to find a file that the source code can't.

I'm working on Windows XP, using bloodshed, programming in C, console application.

##### Share on other sites
Jan-Lieuwe    206
Quote:
Original post by JavaMava
Quote:
Original post by Jan-Lieuwe
Quote:
Original post by JavaMava
Quote:
 Original post by Jan-LieuweYour windows would only disappear if the CPU executes one of those 'exit(1)' statements. Those are executed when your program doesn't find 'input.txt' or when it cannot generate 'output.txt' (the latter being unlikely). Is 'input.txt' in the same folder as your executable?All C / C++ projects would generate an .exe file, btw. So I don't understand what you're referring to when you say: "Why is it making an .exe as my other programs never have." - unless your previous projects were written using a different language.

I guess it muse be one of the exit commands, I'll go try that. It does find input.txt though as when I run the .exe it takes the text inside the input.txt and displays it on screen. Yes input.txt is in the same folder.

As for the confusion around generating .exe files, that must be my own mistake. We use a text based network, phobos, in my college so I never really see all my files unless I'm specifically looking for them. I guess when I'm at my home PC I just never noticed the .exe.

Ah, what system are you working on? I was sort of assuming you were creating a console application using Visual C++ on a Windows machine. system("pause"); isn't very portable!

If you see the output, then input.txt definitely can be found and the output.txt file can be generated. So it's not executing one of the exit calls then.

Another thing I used to use:

/* include this */
#include <conio.h>

/* use this to wait for a key */
while (!kbhit())
{
/* waiting for key... */
}

(but I don't think that's part of the ANSI C standard either... getch() is another option)

my issue right now is if I run the .exe it works. If I run it from blood shed it displays "Input file not opened". I removed the exit's. So that explains why it wasn't staying up, however what would cause the .exe to find a file that the source code can't.

I'm working on Windows XP, using bloodshed, programming in C, console application.

The working directory, when running from bloodshed, is obviously not the directory where your .exe resides in. In Visual C++ you can set the working directory. I don't know bloodshed, so I don't know if it's possible there.

You could hardcode the path into the fopen call to bypass the problem at least, like:

fopen("c:\\projects\\input.txt", "rt");

(this is not good practice though :)

##### Share on other sites
JavaMava    190
Okay, well... thanks very much for helping me out. I think I've got it down as much as I can right now.

Thank you.

##### Share on other sites
Jan-Lieuwe    206
Quote:
 Original post by JavaMavaOkay, well... thanks very much for helping me out. I think I've got it down as much as I can right now.Thank you.

Good luck with your assignment ;)

##### Share on other sites
JavaMava    190
dammit, I thought I had this. Heres my issue. It claims it's finding my file, but when I output it to screen all I get are a bunch of rubbish characters.

#include <stdio.h>main() {/********* STEP 1 - define the files *****/  FILE *in;  char line[81], filename[81] = " ";  printf("Enter a file name: ");  gets(filename);/********* STEP 2 - open the files for processing *****/  in = fopen(filename, "r");  if (in == NULL){    printf("Cannot open %s\n", filename);    }  else {    printf("I found %s\n", filename);    printf("%s", line);  }/********* STEP 4 - close the files *****/  fclose(in);  system("pause");}

the file I'm opening is called "name.txt" Inside it has "Joe Smith" and nothing else. I'm getting the "I found name" text, and then under that it prints out /, a heart, ^, ect... you know rubbish. What am I doing wrong?

##### Share on other sites
Cromulent    398
You need to use fread(). You are not actually reading anything from the file at the moment.

##### Share on other sites
The Death    122
I think you can read and write file with library CTextFileDocument.

CTextFileDocument lets you write and read text files with different encodings (ASCII, UTF-8, Unicode 16 little/big endian are supported).

##### Share on other sites
Cromulent    398
Quote:
 Original post by The DeathI think you can read and write file with library CTextFileDocument. CTextFileDocument lets you write and read text files with different encodings (ASCII, UTF-8, Unicode 16 little/big endian are supported).You can download free at http://www.codeproject.com/file/textfiledocument.asp

I was under the impression that he wanted to use only stdio functions.

## Create an account or sign in to comment

You need to be a member in order to leave a comment

## Create an account

Sign up for a new account in our community. It's easy!

Register a new account