I'm new to the subject of splitting files and header files in C.
I get a Segmentation fault (core dumped) when i'm trying to run main. I don't get any more errors.
I tried to trace the problam and I think it is the line:
syntax_check(fp, symb_table, &IC, &DC); in the main.c.
I'm just trying to pass from main.c the parameters *fp and another array strcture(symbol[]) to a function in syntax_check(in syntax_check.c) and do some actions.
main.c:
#include "main.h"
int main()
{
FILE *fp;
int DC=0;
int IC=100;
symbol symb_table[20];
if (!(fp=fopen("file.txt", "r")))
{
printf("Error opening file");
exit(0);
}
syntax_check(fp, symb_table, &IC, &DC);
fclose(fp);
return 0;
}
main.h:
#include <stdlib.h>
#include <stdio.h>
typedef struct {
char name[10];
int address;
int external;
int action;
} symbol;
int syntax_check(FILE*, symbol[], int*, int*);
syntax_check.c:
#include "syntax_check.h"
int syntax_check(FILE *fp, symbol symb_table[], int *IC, int *DC)
{
char buff[80]; /*line to read*/
char buff2[20]; /**/
int i=0;
fgets (buff, 80, fp);
while (buff[i]!='\0'||buff[i]!=' '||buff[i]!='\t')
{
buff2[i]=buff[i];
i++;
}
buff[i]='\0';
if (exist(buff2))
printf("legal");
else
printf("illegal");
return 0;
}
syntax_check.h:
#include <stdlib.h>
#include <stdio.h>
typedef struct {
char name[10];
int address;
int external;
int action;
} symbol;
FILE *fp;
int exist(char action[]);
Related
I cannot manage to solve the error, even though I've used these types of structures in other project in the same manner and it worked.
Meanwhile I'm not getting an errors in the declaration or initialisation of my structures.
The idea is to read information about a bunch of cars from a binary file.
It tells me that "struct Car" is an incomplete type and not allowed.
Here's the code I've made so far:
car.c
#include <stdio.h>
#include <string.h>
#include "car.h"
#define MAX_NUMBER_OF_CARS 10
struct Car importedCars[MAX_NUMBER_OF_CARS];
struct Config importedConfigs[MAX_NUMBER_OF_CARS];
int main( int argc, char* argv[]){
FILE *fp;
fp = fopen("cars.bin","rb");
if(fp != NULL)
{
fread(importedCars,sizeof(struct Car),MAX_NUMBER_OF_CARS,fp);
printf("1. Binary File read, structures of cars created.\n\n");
for(int i = 0; i < MAX_NUMBER_OF_CARS; i++)
{
printf("%s\t%s\t%s\t%d\t%f\t%f\t%f\t%d\n", importedCars[i].make, importedCars[i].model, importedCars[i].configuration.fuelType, importedCars[i].power, importedCars[i].torque, importedCars[i].fuelConsumption, importedCars[i].co2PerKm, importedCars[i].price);
}
}
else
{
printf("cannot read file.\n");
}
fclose(fp);
return 0;
}
car.h
#ifndef _CAR_H_
#define _CAR_H_
#define fuelLength 10
#define gearLength 10
#define conditionLength 10
#define makeLength 30
#define modelLength 30
typedef struct {
char fuelType[fuelLength];
char gearType[gearLength];
int numGears;
char condition[conditionLength];
} Config;
typedef struct {
char make[makeLength];
char model[modelLength];
Config configuration;
short power;
float torque;
float fuelConsumption;
float co2PerKm;
int price;
} Car;
#include <unistd.h>
#include <pwd.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
uid_t userIdFromName(char *name)
{
struct passwd* pwd;
pwd=getpwnam(name);
if(pwd==NULL)
{
perror("gepwnam\n");
exit(EXIT_FAILURE);
}
return pwd->pw_uid;
}
int main(int argc, char* argv[])
{
uid_t uid;
int totalEntries=0;
DIR* dir;
struct dirent* newFile;
char strUID[65];
if(argc<1)
{
fprintf(stderr,"The format is: %s name",argv[0]);
exit(EXIT_FAILURE);
}
uid=userIdFromName(argv[1]);
dir=opendir("/proc/");
sprintf(strUID,"%d",uid);
while((readdir(dir))!=NULL)
{
totalEntries++;
}
char* dirNames[1000];
char* dirIds[1000];
int newCount=0;
dir=opendir("/proc/");
while((newFile=readdir(dir))!=NULL)
{
char statusFilePath[65]="/proc/";
strcat(statusFilePath,newFile->d_name);
strcat(statusFilePath,"/status");
FILE* statusFile=fopen(statusFilePath,"r");//one of the file has been opened;
size_t size;
char* lineData;
if(statusFile==NULL)
continue;
int currentPoisition=0;
while((getline(&lineData,&size,statusFile))!=-1)
{
if(strncmp("Uid:",lineData,strlen("Uid:"))==0)
{
char* dataLine;
currentPoisition=ftell(statusFile);
fseek(statusFile,0,SEEK_SET);
if(strstr(lineData,strUID)!=NULL)
{
int forName=0,forPid=0;
while((getline(&dataLine,&size,statusFile))!=-1)
{
if(strncmp("Name:",dataLine,strlen("Name:"))==0)
{
printf("%s\n",dataLine);
dirNames[newCount]=dataLine;
forName=1;
}
if(strncmp("Pid:",dataLine,strlen("Pid:"))==0)
{
printf("%s\n",dataLine);
dirIds[newCount]=dataLine;
forPid=1;
}
if(forName==1&&forPid==1)
{
newCount++;
}
}
}
fseek(statusFile,0,SEEK_SET);
fseek(statusFile,currentPoisition,SEEK_SET);
}
}
}
/* int runner=0;
while(runner<newCount)
printf("%s\n",dirNames[runner++]);*/
}
I have been unable to understand the core-dumps generated for this program.The program crashes halfway. Here is the core-dump info:
Program terminated with signal SIGSEGV, Segmentation fault.
#0 0x00007f4ed8699d9c in _nss_files_getpwnam_r (name=0x0, result=0x7f4ed8896140 , buffer=0x559f75c7e2a0 "root", buflen=1024, errnop=0x7f4ed889a4c0) at nss_files/files-pwd.c:32
32 nss_files/files-pwd.c: No such file or directory.
I thank you for your help.
Have you qualified the contents of argv[1] before using it here?
uid=userIdFromName(argv[1]);
Also, among other issues, using a variable created as:
char* lineData;
in a function such as:
while((getline(&lineData,&size,statusFile))!=-1)
Will likely cause a seg-fault, as you are attempting to write to a location that you do not own.
Same for:
char *dataLine;
...
while((getline(&dataLine,&size,statusFile))!=-1)
etc.
Create memory and an address for these (and any other like them) before using.
eg:
size_t size = 1000;
char *lineData = malloc(size*(sizeof(*lineData));
if(lineDate)
{
//continue to use lineData
free(lineData);//when done using it
...
I have created the following program. I have not finished with the entire code yet. When I compile the program I get this error:
'expected expression before char'
on line 44.
Here's my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char** scan(FILE *fin, int *n);
void sort(char **array, int n);
void print(FILE *fout, char **array, int n);
int main(int argc, char *argv[])
{
FILE *fp,*dat;
int n;
char **niz;
fp=fopen(argv[1],"r");
dat=fopen(argv[2],"w");
niz=scan(fp,&n);
printf("%d", n);
sort(niz,n);
print(dat,niz,n);
fclose(fp);
fclose(dat);
free(niz);
{
char** scan(FILE *fp, int *n)
{
int c,m=0,g=0;
char **niz;
niz=(char**)calloc(1,sizeof(char *));
niz[0]=(char*)calloc(21,sizeof(char));
while((c=fgetc(fp)!=EOF))
{
if((c>64 && c<91) || (c>96 && c<123))
niz[m][g++]=c;
else if(niz[m][0]!=0)
{
m++;
g=0;
niz=(char**)realloc(niz,(m+1)*sizeof(*char));
niz[m]=(char*)calloc(21,sizeof(char));
}
}
if(niz[m][0]==0)
*n=m;
else *n=m-1;
return niz;
}
Check the closing brace of the main function
I'm a beginner in C language. After reading the initial chapters of Ritchie's book, I wrote a program to generate random numbers and alphabets.
The program compiles fine with gcc. However on running it, it gives an error "Segmentation fault", which is incomprehensible to my limited knowledge. I'd be glad to understand what I've written wrong.
#include <stdio.h>
#include <stdlib.h>
#include "conio.h"
#include <time.h>
long int genrandom(int,int);
void randAlph(void);
char letterize(int);
int main (void) {
// char full[9];
// char part_non[4];
srand(time(0));
int i;
for (i=0;i<50;++i) {
randAlph();
};
}
long int genrandom(int mino,int maxo) {
int val=mino+rand()/(RAND_MAX/(maxo-mino)+1);
return val;
}
void randAlph (){
int val;
char text;
val=genrandom(0,26);
// return val;
text=letterize(val);
printf("%s ,",text);
}
char letterize(int num) {
char letter='A'+num;
return letter;
}
printf("%s ,",text); is wrong - it says that text is a nul-terminated array of chars. Use
printf("%c ,", text);
instead to print your single char.
#include <stdio.h>
#include <stdlib.h>
#include "conio.h"
#include <time.h>
int genrandom(int,int);
void randAlph(void);
char letterize(int);
int main (void) {
// char full[9];
// char part_non[4];
srand(time(0));
int i;
for (i=0;i<50;++i) {
randAlph();
};
}
int genrandom(int mino,int maxo) {//changed function return type to int
int val=mino+rand()/(RAND_MAX/(maxo-mino)+1); //Be careful when you are using '/' operator with integers
return val; //returning int here why set return type to long int?
}
void randAlph (){
int val;
char text;
val=genrandom(0,26);
// return val;
text=letterize(val);
printf("%c ,",text);//Replace %s with %c
}
char letterize(int num) { //No bound checking on num eh?
char letter='A'+num;
return letter;
}
That's all I had to say. :)
Why use %s when text is char. You dont need a string type in the function. Just a char would do. Change in the function : void randAlph ()
printf("%s ,",text);
to
printf("%c ,", text);
This function is supposed to get a parameter as the pointer of a file and put all file into the struct anagram, then write it to another file. Right now the data only contains a.word, but it suppose to containst a.sorted too? I have check the a.sorted using printf
and it printf out the correct data, but why its not writing to the data file?
It still cant get the a.sorted even if i increase the count of the frwite
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include "anagrams.h"
#define SIZE 80
//struct
struct anagram {
char word[SIZE];
char sorted[SIZE];
};
void buildDB ( const char *const dbFilename ){
FILE *dict, *anagramsFile;
struct anagram a;
//check if dict and anagram.data are open
errno=0;
dict= fopen(dbFilename, "r");
if(errno!=0) {
perror(dbFilename);
exit(1);
}
errno=0;
anagramsFile = fopen(anagramDB,"wb");
char word[SIZE];
char *pos;
int i=0;
while(fgets(word, SIZE, dict) !=NULL){
//get ripe of the '\n'
pos=strchr(word, '\n');
*pos = '\0';
strncpy(a.word,word,sizeof(word));
//lowercase word
int j=0;
while (word[j])
{
tolower(word[j]);
j++;
}
/* sort array using qsort functions */
qsort(word,strlen(word), 1, charCompare);
strncpy(a.sorted,word,sizeof(word));
//printf(a);
fwrite(&a,1,strlen(word)+1,anagramsFile);
i++;
}
fclose(dict);
fclose(anagramsFile);
}
it suppose to contains data with a.sorted for example "10th 01ht"
data:
fwrite(&a,1,strlen(word)+1,anagramsFile); should have been fwrite(a.sorted,1,strlen(a.sorted)+1,anagramsFile); I assume the declaration of sorted as char sorted[SOME_LEN];