how to read string cointaing more than one word stored on text file

I want to read string of multipal word stored on text file. I have tried but unable to read it . How this is to be done in c

Here is my code

#include<stdio.h>
main()
{
FILE *fp;
struct human_info
{

char name[40];
char sex;
int age;
};

struct human_info a;
printf("\n Enter name :);
gets(a.name);
printf("\n Enter sex :")
scanf("%c",&a.sex);
printf("\n Enter age ");
scanf("%d",&a.age);

/* Writing data to file */
fp=fopen("temp.txt","a");
fprintf(fp,"\n %s %c %d",a.name,a.sex,a.age);
fclose(fp);

/* reading data from file */

fp= fopen("temp.txt","r");
while(fscanf(fp,"%s%c%d",a.name,&a.sex,&a.age)!=EOF)
printf("\n %s %c %d",a.name,a.sex,a.age)
return(0);
}
Last edited on
closed account (S6k9GNh0)
1. Don't use gets().
2. There are tons of examples on how to do this:

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
// load a file into memory
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  int length;
  char * buffer;

  ifstream is;
  is.open ("test.txt", ios::binary );

  // get length of file:
  is.seekg (0, ios::end);
  length = is.tellg();
  is.seekg (0, ios::beg);

  // allocate memory:
  buffer = new char [length];

  // read data as a block:
  is.read (buffer,length);

  is.close();

  cout.write (buffer,length);

  delete[] buffer;
  return 0;

^ is an example of seekg and tellg functions which are use to load the contents of a file into a text buffer.
Last edited on
look at getline()

think of using a loop to read each line individualy
Topic archived. No new replies allowed.