this output
Andrew Tanenbaum, David Wetherall
Computer Networks
Michaell Donahoo, Kenneth Calvert
TCP/IP Sockets in C
William,Stallings
Yale Patt, Sanjay Patel
is the result of this code.
#include <stdio.h> /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket() and bind() */
#include <arpa/inet.h> /* for sockaddr_in and inet_ntoa() */
#include <stdlib.h> /* for atoi() and exit() */
#include <string.h> /* for memset() */
#include <unistd.h> /* for close() */
#include "./book.h"
#ifndef fileget_C
#define fileget_C
#endif // fileget_C
void readlib(Book* Library){
/*char stock[4][125];*/
FILE *bookfile=fopen("/home/ninja/Sockets/bookstock.txt","r+");
size_t len=0;
int num;
ssize_t read;
char *stringin;
char *isbn;
int *numin;
int n;
for(n=0; n<4; n=n+1){
getline(&stringin, &len, bookfile);
strncpy(Library[n].isbn,stringin,strlen(stringin));
//printf("%s",Library[n].isbn);
stringin=NULL;
getline(&stringin, &len, bookfile);
strncpy(Library[n].Author,stringin,strlen(stringin));
//printf("%s",Library[n].Author);
stringin=NULL;
getline(&stringin, &len, bookfile);
strncpy(Library[n].title,stringin,strlen(stringin));
//printf("%s",Library[n].title);
stringin=NULL;
getline(&stringin, &len, bookfile);
num=atoi(stringin);
Library[n].edition=num;
//printf("%d\n",Library[n].edition);
stringin=NULL;
getline(&stringin, &len, bookfile);
Library[n].year=atoi(stringin);
stringin=NULL;
//printf("%d\n",Library[n].year);
getline(&stringin, &len, bookfile);
strncpy(Library[n].publisher,stringin,strlen(stringin));
stringin=NULL;
getline(&stringin, &len, bookfile);
Library[n].inventory=atoi(stringin);
stringin=NULL;
getline(&stringin, &len, bookfile);
Library[n].available=atoi(stringin);
//printf("%d\n",Library[n].available);
}
// printf("%s",Library[0].title);
//printf("%s",Library[1].title);
//printf("%s",Library[2].title);
//printf("%s\n",Library[3].title);
printf("%s",Library[0].Author);
printf("%s",Library[1].Author);
printf("%s",Library[2].Author);
printf("%s",Library[3].Author);
}
出于某种原因,我存储了额外的行,或者我没有以适当的方式存储到指针。 for 循环中注释掉的打印行显示正确的信息,包括打印结构的适当作者字段。
最佳答案
问题出在您的 readlib()
和您的 Library
上。
请注意,readlib()
的return
不是Book*
类型,而您返回Library
属于 Book[]
类型,因此编译器会向您发出警告。
此外,您似乎正试图返回
C 中的数组
。Be very careful .从技术上讲,您可以像这样更改 readlib()
的 return
:
Book* readlib()
但强烈不推荐。最好在函数外部声明数组,并且函数中包含 Book*
参数:
void readlib(Book* Library, int noOfBook)
然后你声明你的
Book Library[4]; //somewhere else
然后像这样调用readlib
:
readlib(Library, 4);
您不需要:
return Library;
在readlib
中,因为它已经在外部声明并传递给readlib
当然,如果你真的想return
Book*
但是,你可以在函数中使用malloc
来准备合适的内存空间:
Book* readlib(int noOfBook){
Book *Library = malloc (noOfBook * sizeof(Book));
//something else
return Library;
}
但我个人更喜欢在外面处理所有这些。
关于c - 如何传递结构编辑[如何存储行],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35498338/