我在将文本输入char数组时遇到了一些麻烦。当我为数组设置静态大小时,它工作正常,如
char speech[15000];
但效率低下,所以我尝试使用calloc。这使它停止工作。数组的大小合适,但没有任何内容写入。这是相关的代码。我做错了什么?
int main() {
FILE* inFile;
int i;
int count = 0;
printf("\nOpening file April_30_1789.txt\n");
inFile = fopen("./speeches/April_30_1789.txt", "r");
if(inFile == NULL) {
printf("Could not find April_30_1789.txt\n");
return -1;
}
char ch;
while((ch = fgetc(inFile) != EOF)) count++;
rewind(inFile);
int size = count;
printf("Size of the array is %d\n", size);
char *speech = (char *)malloc(size*sizeof(char) + 1*sizeof(char));
fscanf(inFile, "%s", speech);
printf("Closing the file.\n");
fclose(inFile);
printf("%s", speech);
printf("\n\nDone\n");
return 0;
}
目前,这给了我
Opening file April_30_1789.txt
Size of the array is 8617
Closing the file.
Fellow-Citizens
Done
答案 0 :(得分:8)
Reading the whole text file into a char array in C可能重复。
fscanf
格式的 您的问题:"%s"
会读到遇到的第一个空格。
可能的解决方案(为简明起见,省略了错误检查):
#include <stdio.h> /* printf */
#include <stdlib.h> /* fopen, fseek, ... */
char *buffer = NULL;
size_t size = 0;
/* Open your_file in read-only mode */
FILE *fp = fopen("your_file_name", "r");
/* Get the buffer size */
fseek(fp, 0, SEEK_END); /* Go to end of file */
size = ftell(fp); /* How many bytes did we pass ? */
/* Set position of stream to the beginning */
rewind(fp);
/* Allocate the buffer (no need to initialize it with calloc) */
buffer = malloc((size + 1) * sizeof(*buffer)); /* size + 1 byte for the \0 */
/* Read the file into the buffer */
fread(buffer, size, 1, fp); /* Read 1 chunk of size bytes from fp into buffer */
/* NULL-terminate the buffer */
buffer[size] = '\0';
/* Print it ! */
printf("%s\n", buffer);
答案 1 :(得分:1)
正如pmg所说,while((ch = fgetc(inFile) != EOF)) count++;
使你的文件指针指向最后,使用rewind(FILE* fileptr);
返回文件的开头。
答案 2 :(得分:1)
您的文件指针inFile
指向结束
我会做以下事情:
long lSize;
fseek( inFile , 0L , SEEK_END); //use the function instead
lSize = ftell( inFile ); // to know the file size
rewind( inFile ); // Now point to beginning
char* speech = calloc( 1, lSize+1 );
if( speech )
{
if( fread( speech , lSize, 1 , inFile) != 1)
{
fclose(inFile) ;
free(speech);
exit(1);
}
}
// Process the speech Here
fclose(inFile);
free(speech); // Don't forget to free the allocated memory !