reading from one file and writing to another

Joined
May 22, 2008
Messages
1
Reaction score
0
Hi there

i am new to this C programming, so please dont laugh at my code! i have only been using C for a week!

anyway. my problem is this. i have a file called file.txt, that has lots of data in lines. the data is repeated many times. what i want to do is open the file.txt, read each line in turn, then copy that line into another file called parsed.txt. but i dont want the lines repeated in parsed.txt, just each line as one entry

for example

in file.txt i have

cat
dog
fish
pillow
cat
cat
dog
dog

etc. in parsed i just want

cat
dog
fish
pillow

basically all the individual elements without repeating itself.

here is my broken code so far...

#include <stdio.h>
#include <fcntl.h>
#include <string.h>

main()
{
char c[256];
char t[256];
FILE *file, *file2;
file = fopen("file.txt", "r" );
file2 = fopen ("parsed.txt", "w");
fputs ("stuff\n", file2);
fputs ("more stuff\n", file2);
fclose (file2);
file2 = fopen ("parsed.txt", "r");
if (file==NULL)
{
printf ("Unable to open file.\n");
return 1;
}
if (file2==NULL)
{
printf ("Unable to open file2");
}
while (fgets(c, 256, file) !=NULL)
{
printf ("initial string %s\n",c);
rewind (file2);
file2 = fopen("parsed.txt", "r");
while (fgets(t, 256, file2) !=NULL)
{
printf ("second loop entered\n");
printf ("%s : %s", c, t);
if (strcmp (c,t) == 0)
{
printf ("The entry is already in the file\n");
break;
}
else
{
printf ("not in the file\n");
printf ("second printout %s : %s", c, t);
close (file2);
file2 = fopen ("parsed.txt", "a");
fputs (c, file2);
fclose (file2);
break;
}
}
}
fclose (file2);
printf ("reached the end\n");
}

can anyone tell me what i am doing wrong?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top