error:’ undeclared (first use in this function) - c

I have a header file named store.h which contains a struct and my main is located in E.c,i am currently experiencing an error which i can not comprehend why it is happening. Any help is much appreciated
store.h:
struct st{
char *buf,*var;
int line_number;
char *keywords;
char *operators;
};
E.C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "store.h"
#define max 1000000
int main(int argc,char *argv[]){
FILE *fp;
int ag=0;
fp=fopen( argv[1],"r");
if(fp==NULL){
printf("error cannot open file\n");
exit(1);
}
while(feof(fp)==0){
*buf=fgets(*buf,max,fp);
// irrelevant commands follow
}
fclose(fp);
}
On the line *buf=fgets(*buf,max,fp); I get the error:‘buf’ undeclared (first use in this function), however I have declared it in my struct and I have included the file that contains the struct, where am I wrong?

buf is a member of the struct.
You need to define the struct object.
You need to allocate memory for buf.
You should not assign buf with return value as it may cause a memory leak
Why is “while ( !feof (file) )” always wrong?
int main(int argc,char *argv[]){
FILE *fp;
struct st s;
int ag=0;
s.buf = malloc(max);
if(!s.buf) exit(2);
fp=fopen( argv[1],"r");
if(fp==NULL){
printf("error cannot open file\n");
exit(1);
}
while(fgets(s.buf,max,fp)){
/* ...*/
}
/* .... */

Related

Seg. Fault and not sure why

I am not sure why I am getting a seg fault. I know it is somewhere in my pidspec function but I'm not sure why it is happening. The goal of this program is to have the process id passed in as first argument to program, from there, the pid is located in the proc folder and the contents of that file are displayed to console. Any help would be greatly appreciated. I haven't written any C for a year so I'm a bit rusty.
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>
void pidspec(char *v){
DIR *myDirectory;
struct dirent *myFile;
char *proc = "/proc";
printf("Made it here");
myDirectory = opendir(proc);
if(myDirectory){
printf("Made it here");
if(strcmp(myFile->d_name, v) == 0){
myDirectory = opendir(v);
if(myDirectory){
while ((myFile = readdir(myDirectory)))
printf("%s\n", myFile->d_name);
}
}
}
return;
}
int main(int argc, char *argv[]){
printf("Made it here");
if(argc == 2){
printf("%s",argv[1]);
pidspec(argv[1]);
}
return 0;
}
On your first run, myFile is not initialised, that is not pointing to anything, and then you de-refernece it!
struct dirent *myFile;
...
if(strcmp(myFile->d_name, v) == 0)
So either you didn't mean to use myFile here, or ensure it's pointing at something first.

splitting files in C- Segmentation fault

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[]);

How do I find instances of a file in directory/sub-directories in C?

So I have a program, and with a passed filename, I need to find/open all files with that name that exist in the current directory and all sub-directories.
I do not know the names of the subdirectories. I do not care about their names or any other files, I just need to be able to open all files with the passed name.
Thanks!
Here's an example with ntfw().
#define _XOPEN_SOURCE 500
#include <ftw.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
static int display_info(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf){
char *fileName = "findMe.txt";
/* fpath holds the full path of the file from the specified starting directory */
if ( strstr(fpath, fileName) ){
printf("Match found!\n");
}
return 0;
}
int main(int argc, char **argv){
/* If a starting directory isn't specified, use the current dir */
if (nftw((argc < 2) ? "." : argv[1], display_info, 20, 0) == -1) {
perror("nftw");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}

Segmentation Fault outside the loop only

Using C on Linux, I'm writing a code that stores all the information about the files in a directory using function stat() and prints them on the Terminal
The algorithm is quite simple, I made a structure array of "files" and dynamically allocated them. The structure contains a char array (string) so I dynamically allocated it too.
The thing is .. the dynamic allocation works fine but if I'm inside the while loop I can access the other element inside the structure - which is a structure stat object - but if I access it after the loop finishes, it gives me "Segmentation Fault"!
Here's the code
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
#include <dirent.h>
struct file{
char* name;
struct stat fbuf;
};
int main(int argc, char **argv)
{
char* dir=NULL;
int k;
dir=(char *)malloc(strlen(argv[argc-1])+1);
dir=argv[argc-1];
strcpy(dir,argv[argc-1]);
DIR *curr_dir;
struct dirent *dir_inode;
int i,j=0;
char* sum=NULL;
struct file* files=NULL;
if ((curr_dir = opendir(dir)) == NULL) {
fprintf(stderr, "Can't Open %s\n", argv[1]);
exit(2);
}
while (((dir_inode = readdir(curr_dir))) != NULL) {
files=(struct file*) realloc(files,((j)+1)*(sizeof(char*)+sizeof(struct stat))); // Structure array reallocation
(files+(j))->name=(char *)(malloc(strlen(dir_inode->d_name)+1));//name allocation
for(i=0;i<strlen(dir_inode->d_name);i++)
(files+(j))->name[i]=dir_inode->d_name[i];//name storage
(files+(j))->name[i]='\0';
sum= (char *) malloc(strlen(dir)+strlen(dir_inode->d_name)+2);//To add file name to its directory
for(i=0;i<strlen(dir);i++)
sum[i]=dir[i];
sum[i]='/';
i++;
for(k=0;dir_inode->d_name[k]!='\0';k++)
sum[i+k]=dir_inode->d_name[k];
sum[i+k]='\0';//file name with directory in sum
if( stat(sum,&((files+j)->fbuf)) == -1){ // the function gets information from the file name and stores them in fbuf
printf("error stat\n");
exit(1);
}
free(sum);
if( S_ISDIR( ( (files+(j))->fbuf ).st_mode ) ){
printf("d");
}
else {
printf("-");
}
//Here the output appears fine
//The output depends on accessing fbuf in files array
printf("statOK\n");
(j)++; // index
}
printf("%d %d %d\n",files,j,files+1);
printf("%d\n",j);
printf("\n\n\n\n");
for(i=0;i<j;i++){
printf("%s\n",(files+i)->name);
printf("%d\n",files);
//Starting from here, same syntax but outside the loop it gives the error
if( S_ISDIR( ( (files+i)->fbuf ).st_mode ) ){
printf("d");
else {
printf("-");
}
}
free(files);
free(dir);
closedir(curr_dir);
exit(1);
}
The code isn't complete yet but all what I want is to access the fbuf outside the loop, then I can complete it
Any ideas?
Bad size assumption
This allocation is wrong:
files=(struct file*) realloc(files,((j)+1)*(sizeof(char*)+sizeof(struct stat)));
Here, you assumed that the size of struct file was the sum of the sizes of its two components. But in fact, you don't know how that structure is packed and aligned, so the size of struct file could be larger than what you thought. You should just be using sizeof(struct file) instead:
files=(struct file*) realloc(files,(j+1)*(sizeof(struct file)));

Reading config file in C using libconfig

I defined a structure for options in my config file and a pointer to this structure in "config.h" file and I read config file using libconfig and set values in function get_config() that is defined in file "config.c". In main function I initialize pointer to structure and call get_config() function. libconfig works well and prints values of structure's fields correctly but when I print same fields in main functions their values are incorrect!
"config.h"
#include <stdio.h>
#include <stdlib.h>
#include <libconfig.h>
typedef struct
{
int buffer_size;
const char * DBusername;
const char * DBpassword;
}conf;
conf *config;
int get_config();
"config.c"
#include "config.h"
int get_config()
{
config_t cfg;
config_setting_t *setting;
config_init(&cfg);
/* Read the file. If there is an error, report it and exit. */
if(! config_read_file(&cfg, "config.cfg"))
{
fprintf(stderr, "%s:%d - %s\n", config_error_file(&cfg),
config_error_line(&cfg), config_error_text(&cfg));
config_destroy(&cfg);
return(EXIT_FAILURE);
}
if(config_lookup_int(&cfg, "buffersize", &config->buffer_size))
printf("buffersize: %d\n\n", config->buffer_size);
else
fprintf(stderr, "No 'buffersize' setting in configuration file.\n");
if(config_lookup_string(&cfg, "DBusername", &config->DBusername))
printf("DBusername: %s\n\n", config->DBusername);
else
fprintf(stderr, "No 'DBusername' setting in configuration file.\n");
if(config_lookup_string(&cfg, "DBpassword", &config->DBpassword))
printf("DBpassword: %s\n\n", config->DBpassword);
else
fprintf(stderr, "No 'DBpassword' setting in configuration file.\n");
config_destroy(&cfg);
return(EXIT_SUCCESS);
}
"store.c"
int main(){
config = (conf*) malloc(sizeof(conf));
if(get_config() == EXIT_FAILURE)
return 0;
printf("\n%s", config->DBusername);
printf("\n%s", config->DBpassword);
printf("\n%d", config->buffer_size);
}
The problem is because of defining char* in structure. I changed the char* to char[] and the problem is solved! :)
I defined a structure for options in my config file and a pointer to this structure in "config.h" file...
That statement makes me wonder what a config file is. i.e. is it a .c, or a .h? And what is the visibility to it for other files?
Your issue is likely because the scope (visibilty) of the structure is not provided to the file in which the main() function resides. #include the .h where the struct is defined, and make sure an instantiation of that struct either has global scope, or create an instantiation inside main()
This configuration of files will provide visibility to to main of a struct defined in the .h:
in somefile.h:
typedef struct
{
int membername;
} A_STRUCT;
extern A_STRUCT a
;
in someotherFile.c
#include "somefile.h"
A_STRUCT a = {3}; //global copy of the struct, with assignment
int main(void)
{
printf("%d", a.membername);
return 0;
}

Resources