创建了一个结构,如下所示:
struct entry
{
int source[5];
int destination[5];
int type[5];
int port;
int data;
} record;
用户必须输入文件名,文件需要根据特定条件进行验证然后存储,但我不知道如何在我的代码中使用malloc或calloc函数来允许我这样做。还需要有关如何验证文本文件的帮助。代码片段如下所示:
int file()
{
FILE *inFile;
char inFileName[70]= {'\0'};
char data1[70];
char *token;
int x = 0;
int count = 0;
int length = 0;
printf("Enter File Name:");
scanf("%s", inFileName);
if ((inFile = fopen(inFileName, "r"))== NULL)
{
printf("Open failed:%s\n", inFileName);
exit(1);
}
if (inFile != NULL)
{
while (!feof (inFile)) // Read the whole file until the end of the file.
{
count ++;
printf("\n\nRecord:%i\n", count);
fgets(data1, sizeof data1, inFile); //fgets reads the first string from the "inFile" pointer and stores it in char "data" using the "sizeof" function to make sure strings are the same size.
token = strtok(data1, ":"); // the "token" pointer used with the "strtok" function to break down the "data" string into smaller tokens by using the delimiter ":"
record.source[5] = token;
printf("Source:%d\n", record.source);
答案 0 :(得分:1)
您可以使用它来获取文件大小:
How do you determine the size of a file in C?
然后做一个这样大小的malloc。
off_t size = fsize(inFileName);
char *data = malloc((size + 1) * sizeof(char));
off_t offset = 0;
并在fgets存储数据之后:
fgets(data1, sizeof data1, inFile);
strcpy(data + offset, data1);
offset += strlen(data1);