Hello,

I'm trying to simply copy the text from one .txt and create a new one and copying it to a new txt. I'm actually adding more text to that new file but that's not the part I'm having problems with.

I could go through the entire .txt with this

#include <stdio.h>
void main()
{
  char car;
  FILE *pD, pS;  //Destination and Source
  pD = fopen("DEST.TXT","wt");
  PS = fopen("SOURCE.TXT","rt");
  do
  {
    car = fgetc(pS);
    fprintf(pD,"%c", car);
  }
  while(c!=EOF);
  fcloseall();
}

But I would like to read the source line by line, with a string long enough for the reading. Something like:

char instring[101], fin;
    pD = fopen("DEST.TXT","wt");
    pS = fopen("SOURCE.TXT","rt");
    do
    {
      fgets(instring,100,pS);
      fprintf(pD,"%s", instring);
    }
    while( ????? );

I just don't know what to put in the while or how else to read the file line by line until the end of the file. Knowing how many lines the source has might help, but I'm sure there's gotta be a beter way.
In our class we're not using iostream.h, just stdio.h for I/O.

Also, What's wrong with this piece of code:

#include <stdio.h>
typedef struct Guest
{
  char Name[21];
  char LastName[21];
  char GuestCode[7];
  char Gender;
  int Table;
} TGuest

void Table_Swap()
{
  FILE *pF;
  TGues Reg;
  pF = fopen("GUESTS.DAT","r+b");
  if( pF==NULL )
  {
    printf("FILE ERROR");
    getch();
    return;
  }
  while( (fread(&Reg,sizeof(TGuest),1,pF)) > 0 )
  {
    if( Reg.Table == 5 )
    {
      Reg.Table = 6;
      fseek(pF,sizeof(TGuest)*-1,SEEK_CUR);
      fwrite(Reg,sizeof(TGuest),1,pF);
      //Doesn't need to be  fwrite(&Reg,sizeof(TInvitado),1,pF);
      //right? I tried both ways, shouldn't be that.
    }
    if( Reg.Table == 6 )
    {
      Reg.Table = 5;
      fseek(pF,sizeof(TGuest)*-1,SEEK_CUR);
      fwrite(Reg,sizeof(TGuest),1,pF);
    }
  }
  fclose(pF);
}

void main()
{
  Table_Swap();
}

What that code's supposed to do is change the people from table 5 to table 6 and viceversa. While doing the tracing I noticed that after it would find a guest with table 5 or 6, and it would do the fseek and or fwrite (can't tell when), it seems to go back up to the 2nd entry of the .DAT file. Any thoughts?

Thanks in advance.

Recommended Answers

All 2 Replies

Wonder if it could be possible for you to use ifstream and getline to get the lines and then use this line to put to you output file. This should read the file to the end.

ifstream PS("SOURCE.TXT");
ofstream pD;
pD.open("DEST.TXT");
string line;

while( getline(PS, line) )
{
	pD << line << '\n';
}
pD.close();

or this using FILE*

char iobuf[255] = {0};
while( fgets(iobuf, sizeof(iobuf), pS) )
{
     fprintf(iobuf);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.