[英]How to get the length of the line being read in from fgets and loop over it
我試圖遍歷fgets中一行的每個字符,但是我遇到了錯誤,如下所述。
int main(int argc, char* argv[]) {
char arr[200]
int currS = sizeof(arr) / sizeof(char);
// call readIt function
}
void readIt(char* argv[], char arr[], int currS) {
FILE* file;
file = NULL;
file = fopen(argv[1], "r");
while(fgets(arr, currS, file) != NULL)
for (int i = 0; i < sizeof(arr); i++)
print each char of current line
}
當我在每行上執行for循環時,每行輸出將是文件中第一行的長度。 for循環迭代的次數永遠不會改變。 我該如何更新? 我看了其他SO問題,但它們並沒有很大幫助。
在readIt()
函數中,您需要strlen(arr)
,而不是sizeof arr
。 后者將為您提供char *
的大小,該大小始終是相同的,而不管它可能指向的字符串的長度如何。
您還應該檢查fopen()
的返回NULL
是否不是NULL
,因為fopen()
可能由於多種原因而失敗。
void readIt(char* argv[], char arr[], int currS) {
FILE * file = fopen(argv[1], "r");
if ( file ) {
while( fgets(arr, currS, file) ) {
const int len = strlen(arr);
for ( int i = 0; i < len; ++i ) {
// print each char of current line
}
}
}
}
請注意,此處使用變量len
意味着在開始遍歷字符串之前,您只計算一次字符串的長度,而不是每次遍歷循環都計算該字符串的長度,如果這樣做for ( int i = 0; i < strlen(arr); ++i )
。 如果您要做的只是打印每個字符,則在調用fgets()
之間字符串的長度不會改變,因此多次計算效率不高。
另外,除非出於某種原因,除非您希望main()
的數組包含readIt()
返回后從文件中讀取的最后一行, readIt()
您可以更輕松地在readIt()
自身中定義arr
,以避免將其傳遞給該方法。功能,例如:
void readIt(char* argv[]) {
FILE * file = fopen(argv[1], "r");
if ( file ) {
char arr[200];
while( fgets(arr, sizeof arr, file) ) {
const int len = strlen(arr);
for ( int i = 0; i < len; ++i ) {
// print each char of current line
}
}
}
}
由於arr
現在是readIt()
的實際數組,而不是char
的指針(您不能將數組傳遞給函數,只能將一個地址傳遞給函數),因此sizeof arr
會為您提供數組的實際大小而不是char *
的大小,因此您可以將其傳遞給fgets()
。
該功能:
void readIt(char* argv[], char arr[], int currS) {
FILE* file;
file = NULL;
file = fopen(argv[1], "r");
while(fgets(arr, currS, file) != NULL)
for (int i = 0; i < sizeof(arr); i++)
print each char of current line
}
最好寫成使用arr[]
的實際字符數
建議使用牙套,以免將來出現許多維護難題
建議使用垂直間距以提高可讀性
建議使用注釋以避免將來出現許多維護難題
void readIt(char* argv[], char arr[], int currS)
{
FILE* file = NULL;
if( NULL == (file = fopen(argv[1], "r") ) )
{ // then fopen failed
perror( "fopen failed" );
exit( EXIT_FAILURE );
}
// implied else, fopen successful
// read line from file and echo to user
// note: file lines are considered to be terminated by either a NUL char or newline or EOF
// fgets() assures the line in arr[] has a NUL char termination
while( fgets(arr, currS, file) )
{
int len = strlen(arr); // returns offset to NUL char
// use following if do not want to echo a newline read from the file
if( '\n' == arr[strlen(arr)-1])
{
arr[strlen(arr)-1] = '\0';
len--;
} // end if
printf( "\nNumber of characters in line: %d\n", len );
printf( "%s\n", arr );
} // end while
fclose(file); // cleanup
} // end function: readIt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.