Reading from a file.

Hi, I'm trying to read some lines of text from a file. This is the code that I've got so far, it seems to be working apart from the fact it only reads the first line of text and prints it to the screen.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//A program that calculates the reduced mass of diatomic molecules.
//The following libraries will be used.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
using namespace std;

int main()
{
int selection;//Defines the selection variable to determine the input.

printf("A program that works out the reduced mass of diatomic molecules.\n\n");//Prints the introductory message.
printf("Would you like to input the data from the keyboard or a .txt file?\n");//Allows the user to choose the input.
printf("1. From a .txt file ");
printf("2. From the keyboard\n");
printf(":");
scanf("%d",&selection);//Assigns the value of the selection int variable.

FILE *FP;
char a[100];
printf("Please input a filename including the .txt extension:"); scanf("%s",a);
FP = fopen(a,"r");

if (FP==NULL)
{
    printf("Error Reading File");
}
else if (FP!=NULL)
{
    fgets (a,100,FP)!=NULL;
    printf("%s",a);
    fclose(FP);
}

return 0;
}


I've had a look in the tutorial, but the tutorial seems to be using a different library to the one we've been told to use in my course. For that reason I don't really want to change to a different library. I don't really understand the code that I've used either, it's pretty much been copied and the places I need to change it been changed. Does anyone know of any tutorials that cover reading from a file in relation to the libraries that I'ved used.

Thanks Alex
Looks like this is C code and not c++, try googling "reading a file using c" and see how you go.
(hint: you need a loop to read each line)
Last edited on
Ohhh I didn't realise. Thankyou very much. I'm assuming C code can be run in a C++ file?
yep, most c++ compilers are happy with c as far as i know.
Not exactly a tutorial, but the reference section lists the various functions for file access, and each one is explained with a short code sample. If you are just beginning, it may be hard to decide which functions you need to use, and which are less common. But still, it could be worth a look here:
http://www.cplusplus.com/reference/cstdio/

There's also a tutorial on C file i/o here, http://www.cprogramming.com/tutorial/cfileio.html
Topic archived. No new replies allowed.