[英]Reading integers from file in C
所以我想讀取一個包含整數的文件。 我可以讀第一個數字,但是我怎么讀所有的數字呢? 字符串很簡單,但這是不同的。 我還想以某種方式閱讀它們,然后再將它們添加在一起。 我編輯了代碼,可以全部輸出,但我的另一個問題是如何單獨選擇每個數字,以便添加所需的內容。 例如,如果我只想選擇第一列並將其添加在一起。
數據:
54 250 19
62 525 38
71 123 6
85 1322 86
97 235 14
碼:
#include <stdio.h>
#include <conio.h>
int main()
{
// pointer file
FILE *pFile;
char line[128];
// opening name of file with mode
pFile = fopen("Carpgm.txt","r");
//checking if file is real and got right path
if (pFile != NULL)
{
while (fgets(line, sizeof(line), pFile) != NULL)
{
int a, b, c;
if (sscanf(line, "%d %d %d", &a, &b, &c) == 3)
{
/* Values read, do something with them */
printf("%d %d %d\n",a, b, c);
}
}
//using fgets to read with spaces
//fgets(line,81, pFile);
//printing the array that got the pfile info
//closing file
fclose(pFile);
}
else
{
printf("Could not open file\n");
}
getch();
return 0;
}
最好的方法可能是使用fscanf()
一次讀取一個數字,然后根據需要跳過空白(和換行符)。
或者,您可以使用fgets()
閱讀整行,然后解析/標記該行,在這種情況下,我將為此使用strtol()
,因為它使繼續下一個麻煩變得微不足道了。 但是,這種方法將您限制為最大fscanf()
,而fscanf()
方法不會。
使用fscanf讀取整行,然后將它們全部添加。
您可以按照以下步驟進行操作:
//using fscanf to read
while(EOF != fscanf(pFile,"%d %d %d", &a, &b, &c))
{
//Add all of them
line = a+b+c;
//printing the array that got the file info
printf("%d",line);
//So it will help to remove trailing "\n" and at the end it will help to come out of loop.
if (EOF == fgetc(fp))
{
break;
}
}
#include <stdio.h>
#include <conio.h>
int main()
{
FILE *pFile;
而不是只讀取一行中的一個整數,而是一次讀取所有三個。
// int line;
int v1, v2, v3;
// opening name of file with mode
pFile = fopen("Carpgm.txt","r");
if(NULL == pFile)
{
fprintf(stderr, "Could not open file\n");
goto CLEANUP;
}
添加了一個循環以讀取所有行。
for(;;)
{
使用“ elementsRead”知道何時到達“文件末尾”或“ EOF”。
int elementsRead;
//using fscanf to read
現在(同時)讀取所有三個數字。
elementsRead=fscanf(pFile,"%d %d %d", &v1, &v2, &v3);
if(EOF == elementsRead)
break;
//printing the array that got the pfile info
現在(同時)打印所有三個數字。
printf("%d %d %d\n", v1, v2, v3);
}
CLEANUP:
if(pFile)
fclose(pFile);
getch();
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.