[英]How to read a specific line in a text file in C (integers)
我遇到程序問題(程序的一部分)。 為了進一步繼續,我需要以某種方式讀取文件的一行,但必須是一個特定的行。 我是C和文件的新手......
我想要做的是要求用戶輸入他們想要閱讀的特定行,然后將其顯示給他們。 目前,當我嘗試從行中打印文本時,它只給出了第1行的文本。 請注意,通過文本我的意思是整數,因為該文件由一列中的55個整數組成。 所以它看起來像這樣:12 18 54 16 21 64 .....
有沒有辦法達到我的需要?
#include <stdio.h>
FILE *file;
char name[15];
int line;
int text;
file = fopen("veryimportantfile.txt","r");
if(file==NULL)
{
printf("Failed to open");
exit(1);
}
printf("Your name: ");
scanf("%s",&name);
printf("\Enter the line number you want to read: ");
scanf("%d",&line);
fscanf(pFile, "%d", &line);
printf("The text from your line is: %d",line);
怎么樣:
getc
逐個讀取文件中的字符,直到遇到所需數量的換行減去1 fscanf("%d", ...)
就像是:
int ch, newlines = 0;
while ((ch = getc(fp)) != EOF) {
if (ch == '\n') {
newlines++;
if (newlines == line - 1)
break;
}
}
if (newlines != line - 1)
/* Error, not enough lines. */
/* fscanf loop */
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.