I'm trying to write an array of structs to a file, then read that file into an empty array of structs and print out the variables within each struct element of the array.
my code is below, currently I just have it to try to print the first element, but nothing is printed out to the screen.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct{
char name[1024];
int price;
} game;
void main(){
FILE *filename;
filename = fopen("file.txt","w");
game library[3]; //creation of our game library
//initializing the array to be written, 3 structs inside this array should be written to the file in sizeof(game).
strcpy(library[0].name,"Minecraft");
strcpy(library[1].name,"Opium");
strcpy(library[2].name,"Devil");
library[0].price = 10;
library[1].price = 20;
library[2].price = 30;
fwrite(library,sizeof(game),3,filename);
fseek(filename,0,SEEK_SET);
game second[3];
printf("test");
fread(second,sizeof(game),3,filename);
printf("element 0 is %s $%d",second[0].name,second[0].price);
fclose(filename);
}
Related
As part of a larger project, I am trying to write a function that will allocate enough memory for a struct variable and assign values to its member variables after scanning them from the keyboard. In other words, I am trying to create a sort of a constructor function. The reason for this is because I think that's the best way to create a database-like program in c, where all the student_t variables will be stored in a student_t* array called classroom.
#include <stdio.h>
#include <stdlib.h>
#define N 10
#define STRLIM 50
typedef struct student{
char* name;
int age;
}student_t;
student_t* init_student(student_t* s);
int i=0;//its the array counter
student_t* classroom[N];
int main(int argc, char const *argv[]){
while(i<N){
// classroom[i]=(student*)malloc(sizeof(student));
init_student(classroom[i]);
classroom[i]->age=i;
printf("The age of student #%d is : %d \n",i,classroom[i]->age);
printf("the name of student #%d is : %s",i,classroom[i]->name);
i++;
}
printf("the size of the classroom is : %ld",sizeof(classroom));
return 0;
}//end of main()
student_t* init_student(student_t* s){
s=(student_t*)malloc(sizeof(student_t));
s->name=(char*)malloc(sizeof(char)*STRLIM);
fflush(stdin);
fgets(s->name,STRLIM,stdin);
return s;
}
Gdb ouput shown in the attached image here.
Please check out my repo.
I am guessing something about my build and datatypes is off .Thanks in advance.
I have been working on reading data from a file, which contains student name and age in the format:
John
12
Jane
13
Julia
18
Here's the program I wrote:
#include <stdio.h>
#include <stdlib.h>
struct record{
char name[50];
int age;
};
int main(){
FILE *fp;
fp=fopen("sample2.txt","r");
struct record a[50];
int counter=1;
int i=0;
while (!EOF){
if (counter%2!=0){
fgets(a[i].name,50,fp);
counter++;
}
if (counter%2==0){
a[i].age=getw(fp);
counter++;
i++;
}
}
return 0;
}
However, on printing a[0].name, I am not getting expected output. Can someone help?
As already pointed out in the comments, EOF is a value defined in stdio.h and does not say anything about your file descriptor. I also would recommend you to use fscanf (As long you are sure that the names in the file are all of the correct length). fscanf takes a string similar to printf, specifying the elements you are expecting and returns the number of possible matches. Also it helps you with converting your data to the correct datatypes. So the code could look like this:
#include <stdio.h>
#include <stdlib.h>
struct record
{
char name[50];
int age;
};
int main ()
{
FILE *fp;
fp = fopen ("sample2.txt", "r");
struct record a[50];
int i = 0;
while (fscanf(fp, "%s\n%d\n", (char *) a[i].name, &a[i].age) > 0) {
i++;
}
printf("%s %d\n", a[1].name, a[1].age);
return 0;
}
I have to read a text file using this structure. Also, I have to use external functions. I made the code for file reading and it works in main function.
Text file:
banana 3 orange 8 music 9- first character is a blank space*
#include <stdio.h>
#include <stdlib.h>
struct file
{
char name[30];
char size;
};
int main()
{
int n=0;
struct file f[30];
FILE *files;
files=fopen("files.txt","r");
int n=0;
while (1)
{
fgetc(files);
if(feof(files)) break;
fscanf(files,"%s %c",&f[n].name,&f[n].size);
n++;
}
}
But when I try to make this reading using another c file and extern function it's no working.. :(
This is what is written in filereading.c:
void fileReading(struct file *f[30], FILE *files)
{
int n=0;
while (1)
{
fgetc(files);
if(feof(files)) break;
fscanf(files,"%s %c",&f[n].name,&f[n].size);
n++;
}
}
And fileReading.h:
void fileReading(struct fisier *, FILE *);
And in main.c:
#include <stdio.h>
#include <stdlib.h>
struct file
{
char name[30];
char size;
};
int main()
{
int n=0;
struct file f[30];
FILE *files;
files=fopen("files.txt","r");
fileReading(f[30],files);
}
When I compile it, it says:
request for member 'name' in something not a structure or union
request for member 'size' in something not a structure or union|
||=== Build finished: 2 errors, 2 warnings (0 minutes, 0 seconds) ===||
Can you help me, please? Thank you!
From what I see it looks like you do not have a good understanding of pointers.
These changes should solve your problem:
void fileReading(struct file *f, FILE *files)
{
int n=0;
while (1)
{
fgetc(files);
if(feof(files)) break;
fscanf(files,"%s %c",f[n].name,&f[n].size);
//printf("%s %c",f[n].name,f[n].size);
n++;
}
}
int main()
{
int n=0;
struct file f[30];
FILE *files;
files=fopen("files.txt","r");
fileReading(f,files);
}
What you did wrong:
void fileReading(struct file *f[30], FILE *files) //here you were saying file is a **
fscanf(files,"%s %c",&f[n].name,&f[n].size); // here you need to send the a char* but you were sending a char ** as a second parameter
fileReading(f[30],files); // here you were sending the 31th element of the structure array f which by the way doesn't exist (indexing is from 0 , f[29] is the last) even though that was not what you wanted to do in the first place
The file fileReading.c doesn't know the definition of struct file. You need to move it from main.c to fileReading.h and #include "fileReading.h" in both main.c and fileReading.c.
Also, the definition and call of fileReading is incorrect. Instead of:
void fileReading(struct file *f[30], FILE *files)
You want:
void fileReading(struct file *f, FILE *files)
And you call it like this:
fileReading(f,files);
This is incorrect:
fileReading(f[30],files);
Because you're passing a single struct file instead of the array, and the single instance you're passing is one element off the end of the array (since the size is 30, valid indexes are 0-29), which can cause indefined behavior.
I have a problem in my programming, I totally have no idea why I cannot use qsort in my program to sort these struct array in an ordered way? Can some way help me? in this program, there are 4 Nodes, and the every node represent a file, the node has filename, size and filetype. I want to sort it based on filename, but I totally have no idea why qsort doesn't work at all!
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <unistd.h>
//int cmp(const void *a,const void*b);
typedef struct node
{
char filename[255];
char filetype[255];
long ofilesize;
long newfilesize;
}Node;
Node Line[4];
int cmp(const void *a,const void*b)
{
return strcmp(((Node *)a)->filename,((Node *)b)->filename);
}
int main(){
/* int j=0;
for(;j<4;j++){
Line[j]=(Node*)malloc(sizeof(Node));
}*/
strcpy(Line[0].filename,"b.txt");
strcpy(Line[1].filename,"c.txt");
strcpy(Line[2].filename,"d.txt");
strcpy(Line[3].filename,"e.txt");
int i=0;
for(;i<4;i++){
strcpy(Line[i].filetype,"regular file");
Line[i].ofilesize=i;
Line[i].newfilesize=i;
}
for(i=0;i<4;i++)
{
printf("File %s has type %s original size %ld new size %ld \n",Line[i].filename,Line[i].filetype,Line[i].ofilesize,Line[i].newfilesize);
}
qsort((void *)&Line,4,sizeof(Node),cmp);
for(i=0;i<4;i++)
{
printf("File %s has type %s original size %ld new size %ld \n",Line[i].filename,Line[i].filetype,Line[i].ofilesize,Line[i].newfilesize);
}
}
here is my output:
File b.txt has type regular file original size 0 new size 0
File c.txt has type regular file original size 1 new size 1
File d.txt has type regular file original size 2 new size 2
File e.txt has type regular file original size 3 new size 3
File b.txt has type regular file original size 0 new size 0
File c.txt has type regular file original size 1 new size 1
File d.txt has type regular file original size 2 new size 2
File e.txt has type regular file original size 3 new size 3
What the author of the comment that got deleted said was
int cmp(Node *a,Node *b) {
return strcmp(a->filename,b->filename);
}
should be
int cmp(Node **a,Node **b) {
return strcmp((*a)->filename,(*b)->filename);
}
if you want to keep your pointers.
This is very easy to solve using C++11. Let the compiler handle the memory allocations for you, and avoid all those nasty pointers.
#include <array>
#include <string>
#include <algorithm>
struct Node
{
std::string filename;
std::string filetype;
long ofilesize;
long newfilesize;
};
bool CompareByFilename(const Node& lhs, const Node& rhs)
{
return lhs.filename < rhs.filename;
}
int main()
{
std::array<Node, 4> line;
line[0].filename = "e.txt";
line[1].filename = "d.txt";
line[2].filename = "c.txt";
line[3].filename = "b.txt";
for (unsigned int i = 0; i < line.size(); i++)
{
line[i].filetype = "regular file";
line[i].ofilesize = i;
line[i].newfilesize = i;
}
std::sort(line.begin(), line.end(), CompareByFilename);
}
Consider using an enum for the file type, and are you sure long is always going to be big enough to hold the file size?
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];