get a string from a data file

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
main() {
    FILE *f;
    char str[50];
    f = fopen("data.txt", "w");
    fprintf(f, "%s", "This is a line");
    fclose(f);
    f = fopen("data.txt", "r");
    fscanf(f,"%s", str);
    printf("%s", str); //will print out "This"
    fclose(f);
    getch();
}

Please tell me how to insert a string into a file, then retrieve it.
Is there any way to tell computer where the starting point and ending point are?
Tell me how. Thanks so much!
ps: Is there any suggestion to create a database with fields(columns) and records(rows)?
I think I will use a function call replace_blank (or replace_whitespace) which replace a white space with an underlined score "_", then insert input string to data file. When retrieving string, "_" is replace by " ". Is there any way more efficient?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  ofstream outfile;
  outfile.open ("example.txt");
  string sample("Writing this to a file.");
  outfile << sample;
  outfile.close();

  string sample2;
  ifstream infile;
  infile.open ("example.txt");
  getline (infile, sample2);
  cout << "Read the following from file: " << sample2 << endl;
  return 0;
}


Is there any way to tell computer where the starting point and ending point are?

Starting point and ending point of what?

ps: Is there any suggestion to create a database with fields(columns) and records(rows)?

Write out each row, and then write out an end-of-line, and then the next row, and then another end-of-line, and then the next row, and then another end-of-line...
Last edited on
Starting point and ending point of what?

Sorry, I mean starting point and ending point of a string.
I've solved this problem.
-----
Write out each row, and then write out an end-of-line
what is an end-of-line? I just know EOF = end-of-file.
Show me. Thanks!
I wanna know how to count total records of a database :)
Last edited on
cout << endl; or cout << "/n"; if you prefer. They don't do exactly the same thing in your program, but they will both start a new line in the file.
@Moschops: Thanks!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
#include <string.h>
main() {
    FILE *f;
    f = fopen("data.txt", "r");
    int line = 0;
    char c;
    while((c=fgetc(f))!=EOF) {
        if(c=='\n') {
            line++;
        }
    }
    printf("%d", line);
    getch();
}

Topic archived. No new replies allowed.