S
spike
Im trying to write a program that should
read through a binary file searching for the character sequence "\name\"
Then it should read the characters following the "\name\" sequence
until a NULL character is encountered.
But when my program runs it gets a SIGSEGV (Segmentation vioalation) signal.
Whats wrong?
And is there a better way than mine to solve this task (most likely)
Code:
----------------------------------------------------------------
int main()
{
FILE *fp;
fp = fopen("demo.dem","rb");
char cTkn;
char sName[50];
int i=0,j=0;
while(!(feof(fp)))
{
if(fread(&cTkn, sizeof(cTkn), 1, fp))
{
if(cTkn == ((char)92)) // if the character '\' is found
{
fread(&cTkn, sizeof(cTkn), 1, fp);
if(cTkn == ((char)110)) // if the character 'n' is found
{
fread(&cTkn, sizeof(cTkn), 1, fp);
if(cTkn == ((char)97)) // if the character 'a' is found
{
fread(&cTkn, sizeof(cTkn), 1, fp);
if(cTkn == ((char)109)) // if the character 'm' is found
{
fread(&cTkn, sizeof(cTkn), 1, fp);
if(cTkn == ((char)101)) // if the character 'e' is found
{
fread(&cTkn, sizeof(cTkn), 1, fp);
if(cTkn == ((char)92)) // if the character '\' is found
{
// here the complete "\name\" string has been found
while(cTkn != ((char)0))
{
fread(&sName[j], sizeof(cTkn), 1, fp);
j++;
}
}
}
}
}
}
}
}
i++;
}
printf("Read %d characters!\n", i);
printf("Found: %s",sName);
fclose(fp);
return 0;
}
----------------------------------------------------------------
read through a binary file searching for the character sequence "\name\"
Then it should read the characters following the "\name\" sequence
until a NULL character is encountered.
But when my program runs it gets a SIGSEGV (Segmentation vioalation) signal.
Whats wrong?
And is there a better way than mine to solve this task (most likely)
Code:
----------------------------------------------------------------
int main()
{
FILE *fp;
fp = fopen("demo.dem","rb");
char cTkn;
char sName[50];
int i=0,j=0;
while(!(feof(fp)))
{
if(fread(&cTkn, sizeof(cTkn), 1, fp))
{
if(cTkn == ((char)92)) // if the character '\' is found
{
fread(&cTkn, sizeof(cTkn), 1, fp);
if(cTkn == ((char)110)) // if the character 'n' is found
{
fread(&cTkn, sizeof(cTkn), 1, fp);
if(cTkn == ((char)97)) // if the character 'a' is found
{
fread(&cTkn, sizeof(cTkn), 1, fp);
if(cTkn == ((char)109)) // if the character 'm' is found
{
fread(&cTkn, sizeof(cTkn), 1, fp);
if(cTkn == ((char)101)) // if the character 'e' is found
{
fread(&cTkn, sizeof(cTkn), 1, fp);
if(cTkn == ((char)92)) // if the character '\' is found
{
// here the complete "\name\" string has been found
while(cTkn != ((char)0))
{
fread(&sName[j], sizeof(cTkn), 1, fp);
j++;
}
}
}
}
}
}
}
}
i++;
}
printf("Read %d characters!\n", i);
printf("Found: %s",sName);
fclose(fp);
return 0;
}
----------------------------------------------------------------