我正在读取一个文件,当我读取时,它会逐行读取并打印出来
我真正想要的是我想要一个包含文件中所有字符的字符数组并打印一次,
这是我的代码
if(strcmp(str[0],"@")==0)
{
FILE *filecomand;
//char fname[40];
char line[100];
int lcount;
///* Read in the filename */
//printf("Enter the name of a ascii file: ");
//fgets(History.txt, sizeof(fname), stdin);
/* Open the file. If NULL is returned there was an error */
if((filecomand = fopen(str[1], "r")) == NULL)
{
printf("Error Opening File.\n");
//exit(1);
}
lcount=0;
int i=0;
while( fgets(line, sizeof(line), filecomand) != NULL ) {
/* Get each line from the infile */
//lcount++;
/* print the line number and data */
//printf("%s", line);
}
fclose(filecomand); /* Close the file */
最佳答案
您需要确定文件的大小。一旦你有了它,你就可以分配一个足够大的数组并一次性读取它。
有两种方法可以确定文件的大小。
使用fstat
:
struct stat stbuffer;
if (fstat(fileno(filecommand), &stbuffer) != -1)
{
// file size is in stbuffer.st_size;
}
使用 fseek
和 ftell
:
if (fseek(fp, 0, SEEK_END) == 0)
{
long size = ftell(fp)
if (size != -1)
{
// succesfully got size
}
// Go back to start of file
fseek(fp, 0, SEEK_SET);
}
关于c - 从文件中读取为 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2975931/