当我在C中打开文件时,我目前正在这样做:
int main()
{
FILE *f
f = fopen("employers.dat", "rb");
if(f == NULL)
{
PUTS("can not open the file:\"employers.dat\"");
fclose(f);
exit(-1);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
fclose指针是否必须使用NULL?
我正在读取一个文件,并希望将每一行放入一个数组中的字符串中.文件的长度是任意的,每行的长度是任意的(虽然假设它将少于100个字符).
这是我得到的,而不是编译.基本上这是一个字符数组的数组,对吧?那不应该char** words = (**char)malloc(sizeof(*char));吗?
#include <stdio.h>
#include <stdlib.h>
int main(){
int BUFSIZE = 32767;//max number of lines to read
char** words = (**char)malloc(sizeof(*char));//gives error: expected expression before 'char'
FILE *fp = fopen("coll.txt", "r");
if (fp == 0){
fprintf(stderr, "Error opening file");
exit(1);
}
int i = 0;
words[i] = malloc(BUFSIZE);
while(fscanf(fp, "%100s", words[i]) == 1)//no line will be longer than 100
{
i++;
words[i] = realloc(words, sizeof(char*)*i);
}
int j;
for(j = 0; j < i; j++) …Run Code Online (Sandbox Code Playgroud)