I am trying to get a handle on two things: building strings, and reading a file. I am trying to write a function that will pull a line from a file and put it into a string. I want to use it in a loop, so I am having the function return the EOF status (true or false). I am passing a pointer to the string so it should come out on the other side.
The function works fine internally... if I do a cout
inside the function I can see it does build the string. However, it is not passing the string back to the main program.
Furthermore, the program crashes after it ends. I think it is some sort of memory leak, though I am not allocating any memory.
Any help would be appreciated.
-Dan
#include <iostream>
#include <stdio.h>
using namespace std;
bool getline(FILE *f, char* ln)
{
char ch[1];
bool runFlag=true;
int ps=0;
ln[0]=0;
while ((fgets(ch, 2, f) != NULL) && (runFlag))
{
if ((ch[0]=='\n') || (ch[0]=='\r')) runFlag=false;
if (runFlag==true) {ln[ps++]=ch[0];}
}
ln[ps]=0;
return !runFlag;
}
int main(int argc, char *argv[])
{
FILE *st;
char buf[256];
char *ln = buf;
st = fopen("c:\\work\\clock.txt", "r");
while (getline(st,ln))
{
cout << ln << '\n';
}
fclose(st);
system("PAUSE");
return 0;
}