从文件字符数组阅读 [英] read from file as char array
本文介绍了从文件字符数组阅读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从一个文件reaing,当我读,它需要连成一条线,并打印
我想什么是我想要的char持有所有字符在文件中的数组,一旦打印,
这是code,我有
如果(STRCMP(STR [0],@)== 0)
{
FILE * filecomand;
//字符FNAME [40];
焦线[100];
INT lcount;
/// *读取文件名* /
//的printf(请输入一个ASCII文件的名称:);
//fgets(History.txt,sizeof的(FNAME),标准输入); / *打开文件。如果返回NULL,有一个错误* /
如果((filecomand = FOPEN(STR [1],R))== NULL)
{
的printf(错误打开文件\\ n);
//出口(1);
}
lcount = 0;
INT I = 0;
而(与fgets(线,的sizeof(线),filecomand)!= NULL){
/ *从infile中获取每一行* /
// lcount ++;
/ *打印的行号和数据* /
//的printf(%S,行); } FCLOSE(filecomand); / *关闭文件* /
解决方案
您需要确定文件的大小。一旦你有,你可以分配一个数组足够大,并在一个单一的去阅读它。
有两种方法来确定该文件的大小。
使用 FSTAT
:
struct stat中stbuffer;
如果(FSTAT(的fileno(filecommand),放大器;!stbuffer)= - 1)
{
//文件的大小是stbuffer.st_size;
}
使用 fseek的
和 FTELL
:
如果(fseek的(FP,0,SEEK_END)== 0)
{
长尺寸= FTELL(FP)
如果(大小!= -1)
{
//成功地得到了大小
} //返回文件的开始
fseek的(FP,0,SEEK_SET);
}
I am reaing from a file, and when i read, it takes it line by line, and prints it
what i want exactly is i want an array of char holding all the chars in the file and print it once,
this is the code i have
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 */
解决方案
You need to determine the size of the file. Once you have that, you can allocate an array large enough and read it in a single go.
There are two ways to determine the size of the file.
Using fstat
:
struct stat stbuffer;
if (fstat(fileno(filecommand), &stbuffer) != -1)
{
// file size is in stbuffer.st_size;
}
With fseek
and 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);
}
这篇关于从文件字符数组阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文