小编Jas*_*son的帖子

如果文件指针为null,我是否必须使用fclose()?(C)

当我在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

c

7
推荐指数
1
解决办法
8828
查看次数

将每行文件读入数组

我正在读取一个文件,并希望将每一行放入一个数组中的字符串中.文件的长度是任意的,每行的长度是任意的(虽然假设它将少于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)

c arrays string file-io

5
推荐指数
1
解决办法
3万
查看次数

标签 统计

c ×2

arrays ×1

file-io ×1

string ×1