示例:
三个文件
hi.txt
在txt中:“我们可以成为”
again.txt
txt内部:“曾经”
的人final.txt
txt内部:“知道C”
然后,另一个名为“订单”的文件
将Order.txt
在txt中:
“的 hi.txt; 6 ”
“的 again.txt; 7 ”
“的 final.txt; 3 ”
我想要的:读取第一个文件名,打开它,列出内容,等待6秒,读取第二个名称,打开它,列出内容,等待7秒,读取第三个名称,打开它,列出内容,等待3秒。
如果我这样做而没有打开内容(你会在我的代码上看到第二个)并列出名称,它可以正常工作,但由于某种原因,它不是关于内容的。
orderFile = fopen("order.txt","r");
while(fscanf(orderFile,"%49[^;];%d",fileName,&seconds) == 2)
{
contentFile = fopen(fileName,"r");
while(fscanf(contentFile,"%[^\t]",textContent) == 1)
{
printf("%s\n", textContent);
}
sleep(seconds);
fclose(contentFile);
}
fclose(orderFile);
输出:
我们可以
(等待7秒)
程序以“RUN SUCCESSFUL”结束
EDIT @
现在,正如你们所说,这就是问题所在:
旧
while(fscanf(orderFile,"%49[^;];%d",fileName,&seconds) == 2)
新
while(fscanf(orderFile," %49[^;];%d",fileName,&seconds) == 2)
我有一个“艰难”的时间来完全理解它,空间有什么作用?不接受进入?空间?究竟是什么?
答案 0 :(得分:2)
不要使用fscanf
int
main()
{
FILE *orderFile = fopen("order.txt", "r");
if (orderFile != NULL)
{
int seconds;
char line[128];
/*
* fgets, read sizeof line characters or unitl '\n' is encountered
* this will read one line if it has less than sizeof line characters
*/
while (fgets(line, sizeof line, orderFile) != NULL)
{
/*
* size_t is usually unsigned long int, and is a type used
* by some standard functions.
*/
size_t fileSize;
char *fileContent;
FILE *contentFile;
char fileName[50];
/* parse the readline with scanf, extract fileName and seconds */
if (sscanf(line, "%49[^;];%d", fileName, &seconds) != 2)
continue;
/* try opening the file */
contentFile = fopen(fileName,"r");
if (contentFile == NULL)
continue;
/* seek to the end of the file */
fseek(contentFile, 0, SEEK_END);
/*
* get current position in the stream,
* it's the file size, since we are at the end of it
*/
fileSize = ftell(contentFile);
/* seek back to the begining of the stream */
rewind(contentFile);
/*
* request space in memory to store the file's content
* if the file turns out to be too large, this call will
* fail, and you will need a different approach.
*
* Like reading smaller portions of the file in a loop.
*/
fileContent = malloc(1 + fileSize);
/* check if the system gave us space */
if (fileContent != NULL)
{
size_t readSize;
/* read the whole content from the file */
readSize = fread(fileContent, 1, fileSize, contentFile);
/* add a null terminator to the string */
fileContent[readSize] = '\0';
/* show the contents */
printf("%s\n", fileContent);
/* release the memory back to the system */
free(fileContent);
}
sleep(seconds);
fclose(contentFile);
}
fclose(orderFile);
}
return 0;
}
代码中几乎没有解释所有内容,如果您需要更多信息,请阅读手册。