我發現這段代碼在Reading a file character by character in C,它編譯並且是我想要使用的。我的問題是我無法獲得正確的呼叫。代碼如下:無法打電話工作
char *readFile(char *fileName)
{
FILE *file = fopen(fileName, "r");
char *code;
size_t n = 0;
int c;
if (file == NULL)
return NULL; //could not open file
code = malloc(1500);
while ((c = fgetc(file)) != EOF)
{
code[n++] = (char) c;
}
code[n] = '\0';
return code;
}
我不確定如何調用它。目前我使用下面的代碼來調用它:
.....
char * rly1f[1500];
char * RLY1F; // This is the Input File Name
rly1f[0] = readFile(RLY1F);
if (rly1f[0] == NULL) {
printf ("NULL array); exit;
}
int n = 0;
while (n++ < 1000) {
printf ("%c", rly1f[n]);
}
.....
如何調用ReadFile函數,使得我有一個數組(rly1f),這是不爲空?文件RLY1F存在並且包含數據。我已經成功地打開它以前使用'在線代碼'不是一個函數。 謝謝
'printf(「NULL array」; exit;'could not compile。 – Downvoter
當前'RLY1F'沒有做任何事情,它只是一個空的'char *'指針,你需要爲它指定文本文件的名字。像'char * RLY1F =「myfile.txt」;' – RoadRunner
注意''rly1f'是一個'char' **指針**的數組,所以'printf(「%c」,rly1f [n]);'是未定義,因爲您的格式說明符不匹配。當然是 – Downvoter