[英]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.