[英]Reading content from multiple files in C
例:
三个档案
hi.txt
在txt中: “愿我们成为”
again.txt
txt里面: “曾经的那些人”
final.txt
在txt中: “知道C”
然后,另一个名为“ order”的文件
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”关闭
编辑@
就像你们说的那样,现在可以正常工作,这就是问题所在:
旧:
while(fscanf(orderFile,"%49[^;];%d",fileName,&seconds) == 2)
新:
while(fscanf(orderFile," %49[^;];%d",fileName,&seconds) == 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;
}
代码中几乎没有解释所有内容,如果需要更多信息,请阅读手册。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.