Hi, im new here, as well as a C programming language noob.
Also, i have a school assignment, which i dont expect it to be solved, nor a complete code, but i will need your help in understanding certain things that i completely miss.
Given a certain ficheiro.c with the following in there(example):
Code:
#incluir "something.c"
when i run my program, i expect this to return something.c
(the name of the file prededing #incluir )
/.file2 ficheiro.c
i get the following errors:
Code:
File ficheiro.c successfully opened !!!
1
Segmentation fault (core dumped)
the following code :
Code:
#include <stdio.h>
#include <string.h>
#define MAXLINE 1024
int main(int argc, char * argv[])
{
int i,j,k,n;
char *incluir="#incluir";
char line[MAXLINE];
char file_name[MAXLINE];
FILE *fp;
fp=fopen(argv[1],"r");
if(fp==NULL) /* if it cant open */
printf("File cant be opened %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("1\n"); /* making sure it enters the loop */
if(strstr(line,incluir)!= 0) /* looks for "#incluir" in the line */
{
printf("COOL it exists");
/* in order to copy the name of the file i must first
know until where i will copy */
j=0; n=0;
while( n<=2 )
{
if(line[j] == '\"')
n++;
j++;
}
/* now int j has the position of where ' " ' is */
/* the file *.c has in it -> #incluir "something.h" <-
the first ' " ', occurs at the position 9, so i
will start copying from 9 to j */
for(i=9; k=0, i<j , i++; k++)
{
file_name[k]=line[i];
}
file_name[k+1]='\0'; /* converting it into a string so
i can read it later */
printf("%s \n", file_name);
}
else
{
printf("%s\n", line); /* for debugging purposes */
printf("%s\n", incluir);
printf("OOPS it doesn't");
}
}
}
return 0;
}
when it goes into if(strstr(line,incluir)!= 0) , thats where it goes Segmentation fault, and i know it has to do with memory and for example, it happens when in an array[10], its assigned 100 chars/ints/whatever .
Please help.