how to read file using pointer

Hi all I have been trying to display a txt file using pointer. heres the code, however Im only able to read first 20 character even though I set a while loop.

int main(){
ifstream infile;
char* p;
char buf[20];
infile.open("sample.txt");

while(!infile.eof())
{

infile.getline(buf,20);
p=buf;
for(int i=0; i<strlen(buf);i++)
{

cout << *p;
p++;
}

}
please advise
It works fine for me. Are you sure your file has more than 20 characters?

A couple suggested improvements:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <fstream>
#include <iostream>
using namespace std;

int main()
{
  ifstream infile;
  char* p;
  char buf[20];
  infile.open("sample.txt");

  while (infile)  // note 1
  {

    infile.getline(buf,20);
    for (p=buf; *p; p++)  // note 2
    {
      cout << *p;
    }

  }
  return 0;
}

note 1
It is possible that EOF is never hit if some other error occurrs to set either the failbit or badbit --in which case the eofbit will never be set and you'll have an infinite loop. Test instead against the failbit.

note 2
The getline() function guarantees to null-terminate buf, so just use p until *p is zero. Then you don't need <cstring> or extra calls to functions or signed-to-unsigned conversions, etc.

Hope this helps.

PS Please use [code] tags.
Um... Wouldn't it make more sense to simply use cout <<p? After all, if it's a C string...
ok Thanks. Guess i knw whr im heading to. thanks guys
Topic archived. No new replies allowed.