unexpected ( unwanted ) output in a file
hi, again. I have another problem, this time while writing in a file the lines of another program.
a certain file .h , which will be told to open by a file .c ( first argument ),
and, from that file .h , i will copy each line into another file .txt ( second argument )
if the file .h (mentioned in .c [if #incluir "-----.h" is in it] has the following content:
the output in the .txt file, where i will keep the copy of the lines,will be something like:
this is my program:
Code:
#include <stdio.h>
#include <string.h>
#define MAXLINE 1024
int main(int argc, char * argv[])
{
int j,k;
char *incluir="#incluir";
char line[MAXLINE];
char line2[MAXLINE];
FILE *res;
FILE *h;
FILE *fp;
fp=fopen(argv[1],"r");
res=fopen(argv[2],"w+");
printf(" My first argument was %s\n", argv[1]);
printf(" My second argument was %s\n",argv[2]);
if(fp==NULL) /* if it cant open */
printf("File cant open %s\n",argv[1]);
else
{ /* if it can */
printf("File %s successfully opened !!! \n",argv[1]);
while(fgets(line, MAXLINE , fp)) /* copies the first line */
{
printf("1st while loop, line copied from argv[1]\n"); /* making sure it enters the loop */
if(strstr(line,incluir)!= 0) /* looks for "#incluir" in the line */
{
printf("COOL it exists\n");
/* in order to copy the name of the file i must first
know until where i will copy,
the name is between '"' ( "--------.h" ) */
j=0;
while( line[j++]!='\"');
/* now int j has the position of where
the first ' " ' is */
/* the file *.c has in it -> #incluir "------.h" <-
the first ' " ', occurs at the position j,
but i only need the name, so all it is before
i can shift to the left, therefor... */
for(k=0; k<=MAXLINE-j; k++, j++)
line[k]=line[j];
j=0;
while( line[j++]!='\"');
/* 2nd occurence of '"' */
line[j-1]='\0';
/* the element before the last one,
should be '\0', in order to make it
a string, but i also need to
get rid of '"', so i placed '\0'
before the '"' */
printf("%s \n", line);
/* debugging purposes */
h=fopen(line, "r");
if(h!=NULL)
printf("file %s successfully opened\n", line);
while( fgets(line2, MAXLINE, h))
{
printf("%s\n",line2);
fprintf(res,"%s\n",line2); /* write the line in the h file, to the res file */
printf(" While loop working...\n");
}
}
else
{
printf("%s\n", line); /* for debugging purposes */
printf("%s\n", incluir);
printf("OOPS it doesn't\n");
}
}
}
return 0;
}
although i know the problem is in this loop
Code:
while( fgets(line2, MAXLINE, h))
{
printf("%s\n",line2);
fprintf(res,"%s\n",line2); /* write the line in the h file, to the res file */
printf(" While loop working...\n");
}
When i copy the last line, fgets doesnt copy '\n', and i need that, any advice on how to get over it?