我有一个分配,我要创建一个主函数,它接受一个文本文件(在这种情况下:test.dat),它是解释该文件从堆栈和队列中添加或删除整数。 / p>
我的堆栈和队列正常运行。但是,我不确定如何阅读该文件并让程序实际解释它的含义。
例如:如果文件的第一行显示“add 3”,程序将3推入堆栈并将3排入队列。如果文件的下一行显示“delete”,则弹出堆栈并使队列出列。
就像我说的那样,enqueue / dequeue推/弹功能不是问题。我不知道如何让我的程序实际解释和区分整数,字符,并使用此信息来执行这些功能。
sqjuggler.c :(这是读取文件的主要功能)
#include <string.h>
#include <stdio.h>
#include "sqjuggler.h"
#include "stackADT.h"
#include "queueADT.h"
int main(int argc, char *argv[])
{
Stack inStack, outStack;
Queue inQueue;
inStack = creates();
outStack = creates();
inQueue = createq();
char *filename;
if(argc < 2)
{
printf("Usage: Enter Filename after ./sqjuggler\n");
exit(EXIT_FAILURE);
}else if(argc > 2)
{
printf("Usage: Entered too many file names.\n");
exit(EXIT_FAILURE);
}else {filename = argv[1];}
printf("You entered the filename: %s\n", argv[1]);
FILE *fp = fopen(filename, "r+");
if(fp == NULL)
{
printf("Cant open %s\n", filename);
exit(EXIT_FAILURE);
}
char str[1000];
while(fgets(str, 1000, fp) != NULL)
printf("%s", str);
fclose(fp);
}
现在,它打印出文本文件。就这样。
文字档案:
add 3
add 2
delete
add 5
delete
add 10
add 7
delete
add 0
delete
add 11
delete
delete
delete
控制台:
xxxxxx:~project2$ make j
gcc -o j queueADT.c queueADT.h stackADT.c stackADT.h sqjuggler.c sqjuggler.h
xxxxxx:~project2$ ./j test.dat
You entered the filename: test.dat
add 3
add 2
delete
add 5
delete
add 10
add 7
delete
add 0
delete
add 11
delete
delete
delete
非常感谢任何帮助!
修改
我尝试使用strtok函数将文件拆分为标记。当我实现这个:
char *pch;
pch = strtok(str," \n");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok(NULL, " \n");
}
它只打印了一个额外的“删除”
我不确定如何将整个文件拆分为令牌,然后从那里进行分析。
修改
我将此添加到我的while循环中并获得以下打印输出:
while(fgets(str, 1000, fp) != NULL)
{
printf("%s", str);
char *value = strtok(str, " \n");
printf("%s", value);
}
控制台:
You entered the filename: test.dat
add 3
addadd 2
adddelete
deleteadd 5
adddelete
deleteadd 10
addadd 7
adddelete
deleteadd 0
adddelete
deleteadd 11
adddelete
deletedelete
deletedelete