我有一個練習,我必須讀取一個包含字串的檔案,我必須使用一個/多個陣列回傳內容(這是因為本練習的第二部分要求反轉這些行,我遇到了問題 -因此尋求幫助 - 輸入)。到目前為止,我有這個:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LENGTH 1024
int main(int argc, char *argv[]){
char* input[LENGTH];
if(argc==2){
FILE *fp = fopen(argv[1], "rt");
if(fp!=NULL){
int i=0;
while(fgets(input, sizeof(input), fp)!=NULL){
input[i] = (char*)malloc(sizeof(char) * (LENGTH));
fgets(input, sizeof(input), fp);
i ;
}
printf("%s", *input);
free(input);
}
else{
printf("File opening unsuccessful!");
}
}
else{
printf("Enter an argument.");
}
return 0;
}
我還必須檢查記憶體分配是否失敗。從命令列運行時,當前形式的該程式不回傳任何內容。
編輯:我認為重要的是要提到我收到了一些警告:
passing argument 1 of 'fgets' from incompatible pointer type [-Wincompatible-pointer-types]|
attempt to free a non-heap object 'input' [-Wfree-nonheap-object]|
編輯 2:輸入示例:
These
are
strings
...以及預期的輸出:
esehT
era
sgnirts
在練習中,指定行的最大長度為1024字符。
uj5u.com熱心網友回復:
你可能想要這樣的東西。
注釋在代碼中
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LENGTH 1024
int main(int argc, char* argv[]) {
if (argc == 2) {
FILE* fp = fopen(argv[1], "rt");
if (fp != NULL) {
char** lines = NULL; // pointer to pointers to lines read
int nboflines = 0; // total number of lines read
char input[LENGTH]; // temporary input buffer
while (fgets(input, sizeof(input), fp) != NULL) {
char* newline = malloc(strlen(input) 1); // allocate memory for line ( 1 for null terminator)
strcpy(newline, input); // copy line just read
newline[strcspn(newline, "\n")] = 0; // remove \n if any
nboflines ; // one more line
lines = realloc(lines, nboflines * sizeof(char*)); // reallocate memory for one more line
lines[nboflines - 1] = newline; // store the pointer to the line
}
fclose(fp);
for (int i = 0; i < nboflines; i ) // print the lins we've read
{
printf("%s\n", lines[i]);
}
}
else {
printf("File opening unsuccessful!");
}
}
else {
printf("Enter an argument.");
}
return 0;
}
關于洗掉\n左邊的說明fgets:從 fgets() 輸入中洗掉尾隨換行符
免責宣告:
- 沒有對記憶體分配函式進行錯誤檢查
- 記憶體沒有被釋放。這留作練習。
realloc這里使用的方式不是很有效。- 您仍然需要撰寫反轉每一行并顯示它的代碼。
您可能應該將其分解為不同的功能:
- 讀取檔案并回傳指向行的指標和讀取的行數的函式,
- 顯示讀取的行的函式
- 反轉一行的函式(待寫)
- 一個反轉所有行的函式(待寫)
這留作練習。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/359868.html
