我必须编写一个程序,从文件中读取文本,将其分解成一个结构体,根据一定的标准验证各个部分,然后生成两个新文件;一个有干净的数据,一个有错误。到目前为止,我已经达到了从文件中分解数据并将其存储到结构体中的阶段,但它只适用于前两个变量。文本是由冒号分隔,我需要把每个部分到下面的变量文本文件
的示例0001:0002:0003:0021:CLS
这是结构体
struct packet{
int source;
int destination;
int type;
int port;
char data[50];
};
Bellow是什么工作很好,但是一旦我添加另一个部分添加数据到类型变量,程序不工作。
fscanf(inFile, "%[^:]: %[^:]:", records[i].source, records[i].destination);
printf("%d - %s _ %s", i+1, records[i].source, records[i].destination);
然而,这不起作用,我需要它。我需要在此基础上展开。
fscanf(inFile, "%[^:]: %[^:]: %[^:]:", records[i].source, records[i].destination, records[i].type);
printf("%d - %s _ %s _ %s", i+1, records[i].source, records[i].destination, records[i].type);
}
如果我在没有输入任何东西的情况下打印结构,它会显示null,因为没有任何东西被存储,所以我认为fscanf函数有问题。因为它适用于前两个,我不认为这是一个语法问题,所以它必须是一个内存问题。我用过malloc和realloc,但我搞混了,我肯定我做得不对。
完整代码清单
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//declaration of function which will print my name and student number
const char * myname();
//declaration of a function that will prompt a user to enter a file and open it if it exists
int openfile();
struct packet{
int source;
int destination;
int type;
int port;
char data[50];
};
int main()
{
int recordCount = 0;
struct packet *records;
records =malloc(sizeof(struct packet));
// printing the my name and student number via the myname function
printf("%sn", myname());
//executing the openfile function that will open a function
openfile(recordCount, records);
return 0;
}
const char * myname()
{
const char *x = "*************************nUSERNAMEnUSER NUMBERnCONTACT NUMBERn*************************n";
return x;
}
int openfile(int rCount, struct packet *records)
{
//file pointer which will keep track of the file being accessed
FILE *inFile ;
//creating variable that will hold what the user has entered for a filename to open
char inFileName[100] = { ' '};
printf("Please Enter the File to open:");
//getting the users input and storing it into the variable just created
scanf("%s", inFileName);
//if the file does not exist, display an appropriate error message
if ((inFile = fopen(inFileName, "r")) == NULL)
{
printf("Cannot Open File **%s**n", inFileName) ;
exit(1) ;
}
else {
//if the file does exist, process the data
while(fgets(inFileName, 100, inFile)!=NULL)
{
int i =0;
for (i=0; i<30;i++)
{
fscanf(inFile, "%[^:]: %[^:]: %[^:]:", records[i].source, records[i].destination, records[i].type);
printf("%d - %s _ %s _ %s", i+1, records[i].source, records[i].destination, records[i].type);
}
}
//close the file
fclose(inFile);
return 0;
}
};
你做错了:
fscanf(inFile, "%[^:]: %[^:]:", records[i].source, records[i].destination);
%[]
转换说明符是用于字符串的,但是你把整型的值当作字符指针来传递。未定义的行为!
你应该从任何现代编译器中得到大量的警告,即验证格式化字符串的编译器。
把整数当作字符串来解析是没有意义的,我不明白为什么你不直接做
fscanf(inFile, "%d:%d", &records[i].source, &records.destination);
表示第一种情况。
另外,请注意,使用fgets()
读取整行,然后使用sscanf()
解析该行,而不是尝试将这两个步骤与fscanf()
结合起来,要好得多。
最后,您应该检查转换调用的返回值,以了解成功转换的次数。