我已将 Fprintf 添加到 SavePacket 函数中,但它无法像使用 outpackets 函数那样识别 pos->destination,我如何调整代码,以便它获取保存在我的链接列表和 FprintF 中的数据到我的文件?
void outputPackets(node **head)
{
/*********************************************************
* Copy Node pointer so as not to overwrite the pHead *
* pointer *
**********************************************************/
node *pos = *head;
/*********************************************************
* Walk the list by following the next pointer *
**********************************************************/
while(pos != NULL) {
printf("Source: %i Destination: %i Type: %i Port: %i \n", pos->Source, pos->Destination, pos->Type, pos->Port, pos->next);
pos = pos->next ;
}
printf("End of List\n\n");
}
void push(node **head, node **aPacket)
{
/*********************************************************
* Add the cat to the head of the list (*aCat) allows the *
* dereferencing of the pointer to a pointer *
**********************************************************/
(*aPacket)->next = *head;
*head = *aPacket;
}
node *pop(node **head)
{
/*********************************************************
* Walk the link list to the last item keeping track of *
* the previous. when you get to the end move the end *
* and spit out the last Cat in the list *
**********************************************************/
node *curr = *head;
node *pos = NULL;
if (curr == NULL)
{
return NULL;
} else {
while (curr->next != NULL)
{
pos = curr;
curr = curr->next;
}
if (pos != NULL) // If there are more cats move the reference
{
pos->next = NULL;
} else { // No Cats left then set the header to NULL (Empty list)
*head = NULL;
}
}
return curr;
/************ *************** ************ 保存数据包代码功能 /*********** *************** *************
void SavePacket(){
FILE *inFile ;
char inFileName[10] = { '\0' } ;
printf("Input file name : ") ;
scanf("%s", inFileName) ;
unsigned long fileLen;
//Open file
inFile = fopen(inFileName, "w+");
if (!inFile)
{
fprintf(stderr, "Unable to open file %s", &inFile);
exit(0);
}
fprintf("Source: %i Destination: %i Type: %i Port: %i \n", pos->Source, pos->Destination, pos->Type, pos->Port, pos->next);
}
最佳答案
首先,您应该查看 the function signatures printf
和 fprintf
。 outputPackets
中的 printf
很好。但是,这里是 fprintf
签名:
int fprintf(FILE* stream, const char* format, ...);
第一个参数应该是FILE*
。但是,您这样调用您的函数:
fprintf("Source: %i Destination: %i Type: %i Port: %i \n", pos->Source, pos->Destination, pos->Type, pos->Port, pos->next);
在您的调用中,第一个参数是格式字符串,而它应该是 FILE*
。这就是为什么您没有得到预期结果的原因。
此外,在对 printf
和 fprintf
的调用中,您给出的最后一个值 pos->next
是无用的,您可以删除它。
编辑:准确地说,该行应该是
fprintf(inFile, "Source: %i Destination: %i Type: %i Port: %i \n", pos->Source, pos->Destination, pos->Type, pos->Port);
关于c - FprintF 从链接列表到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16357128/