如何从文件中创建一个char数组?

时间:2015-02-21 04:52:08

标签: c arrays file pointers

#include <stdio.h>
#include <stdlib.h>

int count_arr(FILE *file)
{
 int c,count=0;
//FILE *file;
//file = fopen("test.txt", "r");
if (file) {
    while ((c = getc(file)) != EOF){
        putchar(c);
        ++count;}
    fclose(file);
}
return count;
}

void make_arr (FILE *file, char arr[]){
     int c,n=0,count=0;
     char ch;
//FILE *file;
//file = fopen("test.txt", "r");
if (file) {
    while ((c = getc(file)) != EOF){
    ch = (char)c;
    arr[n]=ch;
    ++n; }
    fclose(file);
}

}


int main(){
FILE *file;
int n;
//scanf("%c",&file_name);
file = fopen("test.txt","r");

int count = count_arr(file);
char arr [count];

make_arr(file, arr);

for(n=0; n<count;++n) printf("%c",arr[n]);

}

到目前为止,这是我的代码所有内容。我知道我做错了。当我打印出char数组时,它会打印随机垃圾...我正在尝试编写一个函数“make_arr”,它传递一个数组,该数组与文件中的字符一起存储。任何帮助,将不胜感激!

1 个答案:

答案 0 :(得分:2)

这是一个将文件读入缓冲区的小例子:

FILE* file = fopen("file.txt", "r");
// get filesize
fseek(file, 0, SEEK_END);
int fsize = ftell(file);
fseek(file, 0, SEEK_SET);
// allocate buffer **note** that if you like
// to use the buffer as a c-string then you must also
// allocate space for the terminating null character
char* buffer = malloc(fsize);
// read the file into buffer
fread(buffer, fsize, 1, file);
// close the file
fclose(file);

 // output data here
for(int i = 0; i < fsize; i++) {
   printf("%c", buffer[i]);
}

// free your buffer
free(buffer);

如果你真的想用一个函数来填充你的缓冲区,这会起作用(尽管我看不到这一点),尽管我仍然只会进行一次读操作:

void make_array(FILE* file, char* array, int size) {
   // read entire file into array
   fread(array, size, 1, file);
}

int main(int argc,char** argv) {
  // open file and get file size by first
  // moving the filepointer to the end of the file
  // and then using ftell() to tell its position ie the filesize
  // then move the filepointer back to the beginning of the file
  FILE* file = fopen("test.txt", "r");
  fseek(file, 0, SEEK_END);
  int fs = ftell(file);
  fseek(file, 0, SEEK_SET);
  char array[fs];
  // fill array with content from file
  make_array(file, array, fs);
  // close file handle
  fclose(file);

  // output contents of array
  for(int i = 0; i < fs; i++) {
    printf("%c\n", array[i]);
  }
  return 0;
}

就像我在上面的评论中所说的那样,如果你想将char数组用作字符串,你需要为终止空字符添加空格:

char* array = malloc(fs + 1);
fread(array, fs, 1, file);
// add terminating null character
array[fs] = '\0';
// print the string
printf("%s\n", array);