C: lists, structures: error: structure has no member - c

English is not my motherlanguage, I'm sorry for any grammar mistakes in the description or in the code, I translated it in order to share it here with you.
Hello, I'm writing a little program in C and I need some help, I'm stuck with one error I can't fix, I searched here on forums and anywhere else, but nothing I found helped me. The other functions in the program work just fine.
This function reads a list of words and categories from txt file, puts it into a structure, makes a list. The user types what word he wants to delete from file, so function searches if it's there and deletes if it is.
I'm not the best with lists so there's probably a really basic, stupid problem here, any help please?
void REMOVE_WORD (int howmanylines)
{
FILE *fp;
if ((fp=fopen("words.txt", "r+w"))==NULL)
{printf("Error while opening the file!\n");
exit(1);}
else
{
typedef struct base
{
struct base *next;
char word[25];
char category[15];
} list_els;
struct base tab[howmanylines];
int i=0;
while (!feof(fp))
{
fscanf(fp, "%s", &tab[i].word);
fscanf(fp, "%s", &tab[i].category);
i++;
}
fclose(fp);
list_els *head;
list_els *el=(list_els*)malloc(sizeof(list_els));
list_els *ind=head;
while (ind->next)
{
ind=ind->next;
ind->next=el;
}
printf("What word do you want to remove?\n\n");
char word_remove[25];
scanf("%s", &word_remove);
if (strcmp(ind->next->word, word_remove)==0)
{
printf("Found:\n Word: | Category:\n %s | %s\n", ind->next->word, ind->next->category);
printf("Are you sure you want to remove?\n1)Yes\n 2)No\n\n");
int removing;
if (removing==1)
{
list_els *removed=ind->next;
ind->next=removed->next;
free(removed);
}
else if (removing==2) {printf("Removing cancelled.\n\n");}
else {printf("Wrong operation number!");}
}
else printf("Word not available in the base!\n\n");
}
}
It shows me an error 'struct base' has no member named 'word' in the line where I use the strcmp.

In this snippet
list_els *head;
list_els *el=(list_els*)malloc(sizeof(list_els));
list_els *ind=head;
while (ind->next)
{
ind=ind->next;
ind->next=el;
}
You are not initialising ind to any valid value. You probably meant to write ind = el instead of head. Also, don't cast malloc().

Related

while loop to build up a list not ending

I'm trying to figure out why my code isn't working but i haven't managed so far. The code should analyse a string and build up a list containing all which letters from the english alphabet (contained in alf) are contained in that string (*s) and how many times:
` char c, *s, alf[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
the string is then acquired from a file and i've got no problem until there, i've managed to print it out correctly on the prompt so that's working. Anyway here's what i did(int variables d and num will be used later):
FILE *f=fopen("prova.txt","r");
int d,l=0,num;
while(feof(f)==0){
l++;
fscanf(f,"%c",&c);
}
s=malloc(sizeof(l*sizeof(char)));
rewind(f);
l=0;
while(feof(f)==0){
fscanf(f,"%c",s+l);
l++;
}
//"stringa acquisita" stands for "acquired string"
printf("\nstringa acquisita:%s",s);
And the string gets printed out correctly, excepting from the fact that it gets one charachter more than it should. Any advices in that direction are also welcome.
So i got to building the list. Here's what I did:
typedef struct Nodo{char car; int rip; struct Nodo* next;} Nodo;
typedef Nodo* lista;
lista head = NULL, el, temp;
for(l=0;l<26;l++){
num=0;
for(d=0;d<strlen(s);d++){
if(s[d]==alf[l]){
num++;
}
}
if(num!=0){
el = malloc(sizeof(Nodo));
if(el==NULL){
perror("error malloc\n");
exit(1);
}
el->car=alf[l];
el->rip=num;
if(head==NULL){
head=el;
el->next=NULL;
//this printf doesn't print anything on the prompt
printf("\n%c\n%d", head->car,head->rip);
}
else{
temp=head;
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=el;
el->next=NULL;
}
}
//this printf prints only one time
printf("CHECKIT\n");
}
And here my code crashes. As i specified in the comments, I put two printf to get to see what's going on. The first one doesn't give anything printed on the prompt, about the second one i get one "CHECKIT" printed out and then everything crashes. Can anyone tell me what I'm missing here?
Thank you a lot.
/EDIT/
There was one sizeof more than it should have been:`
s=malloc(sizeof(l*sizeof(char)));` `
Corrected that with
s=malloc(l*sizeof(char));
everything works correctly.
Thanks everyone.

Unable to write to file in C (using Visual Studio)

So this is my first question here. I'm rather new to both programming and the language C, but if you could help me, that would be much appreciated. In school we have an assignment. I have spoken to a few students in my class, and they use Code blocks, while I use Visual Studio. So I'm trying to write to a file, and it works for one of my friends in Code blocks, and I've tried to do exactly the same (but in visual studio, so I have to use fopen_s instead of fopen) but I can't make it work.
My function, which is supposed to write some items on a grocery list to a file - looks like this:
FILE* file = 0;
char filename[25];
printf("Saving grocery list to test.bin...\n");
The line below is what is different from my friend's code
errno_t errorCode = fopen_s(&file, "test.bin", "wb"); //This line is different
//because of MVS...
if (file == NULL )
{
printf("File could not be opened.\n");
return 0;
}
else
{
fwrite(&totalGrocery, sizeof(int), totalGrocery, file);
fwrite(&item, sizeof(struct grocery), totalGrocery, file);
fclose(file);
printf("The file has now been saved.\n");
}
Okay, so my file that I want to save to is named "test.bin", my grocery list is saved in a struct (called grocery), where item is a pointer to the first item in my grocery list (struct grocery *item) and totalGrocery is my variable for how many struct grocery item that I have saved.
If it's needed, this is what my struct grocery looks like
struct grocery
{
int id;
char food[31];
float quantity;
char unit[16];
};
And every item is made up of one of these struct grocery.
I hope I made myself clear...
Nothing is crashing or anything, but it seems my file never gets anything from the program.
Have I written the fopen_s function wrong? I can't find a lot of information anywhere how it supposed to be written, so I think this might be the case...?

C programming opening and reading from a file

int main(void){
FILE *ifp; //input file pointer
int totalClock; //total clock count
// BEGIN OPERATIONS=============================
ifp=fopen("prog1.asy.txt", "r");
system("PAUSE");
assert(ifp!=NULL);
//populate the instMem with inst===================
int i=0;
//system("PAUSE");
for (i=0;i<512;i++)
{
inst temp=parser(ifp);
if (temp.opcode==-1)
break;
instMem[i]=temp;
printf("%s\n", instMem[i].rawCode);
}
printf("\n%d instructions parsed\n", i-1);
system("PAUSE");// PAUSE TO CHECK CODE PARSING IS CORRECT========
int cont=0;
while (cont==0){
//begin sim================================================
//initialize the mem=======================================
int i;
for (i=0;i<512;i++)
data[i]=0;
for (i=0;i<32;i++)
reg[i]=0;
IF_Time=0;
ID_Time=0;
EX_Time=0;
MEM_Time=0;
WB_Time=0;
//prompt input parameters===================================
printf("Memory access time: c=");
scanf("%d", &c);
printf("\nMultiply time: m=");
scanf("%d", &m);
printf("\nExecute time: n=");
scanf("%d", &n);
assert(c>0);
assert(m>0);
assert(n>0);
//start execution now that the program has been broken to unparsed strings====
while (0==0)
{
WB();
MEM();
if (MEM_WB.instruction.opcode==HALT)
break;
EX();
ID();
IF();
totalClock++;
system("PAUSE");
}
//PRINT RESULTS=============================================
printf("Run again with new parameters? 0=yes");
scanf("%d", &cont);
}
fclose(ifp);
system("PAUSE");
return 0;
}
struct inst parser(FILE *ifp){
char str[100];
struct inst temp;
if (fgets(str, 100, ifp)==NULL) {
inst temp={"NULL", -1,0,0,0};
}
else {
inst temp={str, 0,0,0,0};
puts(str);
}
return temp;
}
I am trying to read in a test file so that i can parse it into strings for analysis later. It opens the test file but it doesn't read the lines of test in the code. Is there something I am doing wrong.
Your parser functions only reads once from the file and does nothing with the result (since temp would be a local variable to the if branch, not to the function). First thing is to remove inst from inst temp = ... to see that it reads the first instruction. Then, you need to make that function loop over all lines in the file.
First of all, you need to format your source code on this page to make it more readable.
For parser(), I don't think you can return a structure. So please use a pointer instead. And, as Mihai mentions, "temp" is a temporary variable located on the stack, and it will be destroyed when returning from function parser().
I don't see the declarations of variables in the code snippet:
IF_Time=0;
ID_Time=0;
EX_Time=0;
MEM_Time=0;
WB_Time=0;
So I assume you could remove some unused code to make the question clear.
The last thing is: to analyze log files, shell scripts is more suitable than C. If you're not working on a UNIX/Linux box, you could also use Perl/Python if you want. They are all less error prone and easy to debug when used to analyze log files.

C Passing file pointer into a function

I have a problem with passing file pointers. How do I pass it if there is a function with a file pointer within a function(void writequest in my code)? It was working before I put in the void writequest. The program itself is supposed to read from one file that is filled with movie names and then put them into another. Of course, feel free to note any other failures in my code.
void writequest(int no)
{
int i, j, loop_ctrl, destination;
int movement;
char lib[loop_ctrl+1][92];
int write_nr[loop_ctrl], sorting[destination];
char searching[92];
char *c;
FILE *watched;
FILE *temp;
FILE *refrom;
FILE *reto;
FILE *towatch;
if(no==1)
{
printf("No match found.\n");
}
else if(no==0)
{
printf("Do you wish you write them into a file?\n1 - Yes\n0 - No\n");
scanf("%d", &j);
if(j==1)
{
tofile(watched, temp, refrom, reto, destination, loop_ctrl, write_nr, lib, movement);
close(towatch, watched, temp, refrom, reto);
remove("To_watch.txt");
rename("temp.txt", "To_watch.txt");
}
else if(j==0)
{
printf("Alright then\n");
close(towatch, watched, temp, refrom, reto);
}
}
}
char *c;
FILE *watched;
FILE *temp;
FILE *refrom;
FILE *reto;
FILE *towatch;
These are all pointers. So if you call upon them in your functions your asking for the value inside them. That's their address. except for movement. What is a bit strange.
It is vital to know what the functions exactly are before anyone can say what the problem is.

Why does my program read an extra structure?

I'm making a small console-based rpg, to brush up on my programming skills.
I am using structures to store character data. Things like their HP, Strength, perhaps Inventory down the road. One of the key things I need to be able to do is load and save characters. Which means reading and saving structures.
Right now I'm just saving and loading a structure with first name and last name, and attempting to read it properly.
Here is my code for creating a character:
void createCharacter()
{
char namebuf[20];
printf("First Name:");
if (NULL != fgets(namebuf, 20, stdin))
{
char *nlptr = strchr(namebuf, '\n');
if (nlptr) *nlptr = '\0';
}
strcpy(party[nMember].fname,namebuf);
printf("Last Name:");
if (NULL != fgets(namebuf, 20, stdin))
{
char *nlptr = strchr(namebuf, '\n');
if (nlptr) *nlptr = '\0';
}
strcpy(party[nMember].lname,namebuf);
/*Character created, now save */
saveCharacter(party[nMember]);
printf("\n\n");
loadCharacter();
}
And here is the saveCharacter function:
void saveCharacter(character party)
{
FILE *fp;
fp = fopen("data","a");
fwrite(&party,sizeof(party),1,fp);
fclose(fp);
}
and the loadCharacter function
void loadCharacter()
{
FILE *fp;
character tempParty[50];
int loop = 0;
int count = 1;
int read = 2;
fp= fopen("data","r");
while(read != 0)
{
read=fread(&tempParty[loop],sizeof(tempParty[loop]),1,fp);
printf("%d. %s %s\n",count,tempParty[loop].fname,tempParty[loop].lname);
loop++;
count++;
}
fclose(fp);
}
So the expected result of the program is that I input a name and last name such as 'John Doe', and it gets appended to the data file. Then it is read in, maybe something like
1. Jane Doe
2. John Doe
and the program ends.
However, my output seems to add one more blank structure to the end.
1. Jane Doe
2. John Doe
3.
I'd like to know why this is. Keep in mind I'm reading the file until fread returns a 0 to signify it's hit the EOF.
Thanks :)
Change your loop:
while( fread(&tempParty[loop],sizeof(tempParty[loop]),1,fp) )
{
// other stuff
}
Whenever you write file reading code ask yourself this question - "what happens if I read an empty file?"
You have an algorithmic problem in your loop, change it to:
read=fread(&tempParty[loop],sizeof(tempParty[loop]),1,fp);
while(read != 0)
{
//read=fread(&tempParty[loop],sizeof(tempParty[loop]),1,fp);
printf("%d. %s %s\n",count,tempParty[loop].fname,tempParty[loop].lname);
loop++;
count++;
read=fread(&tempParty[loop],sizeof(tempParty[loop]),1,fp);
}
There are ways to ged rid of the double fread but first get it working and make sure you understand the flow.
Here:
read=fread(&tempParty[loop],sizeof(tempParty[loop]),1,fp);
printf("%d. %s %s\n",count,tempParty[loop].fname,tempParty[loop].lname);
You are not checking whether the read was successful (the return value of fread()).
while( 1==fread(&tempParty[loop],sizeof*tempParty,1,fp) )
{
/* do anything */
}
is the correct way.
use fopen("data","rb")
instead of fopen("data","r") which is equivalent to fopen("data","rt")
You've got the answer to your immediate question but it's worth pointing out that blindly writing and reading whole structures is not a good plan.
Structure layouts can and do change depending on the compiler you use, the version of that compiler and even with the exact compiler flags used. Any change here will break your ability to read files saved with a different version.
If you have ambitions of supporting multiple platforms issues like endianness also come into play.
And then there's what happens if you add elements to your structure in later versions ...
For robustness you need to think about defining your file format independently of your code and having your save and load functions handle serialising and de-serialising to and from this format.

Resources