尽管问题已被编辑,并且只有部分代码存在问题。我现在发布的内容超出了该问题的要求。原因是,可以对最初发布的完整代码进行大量改进。
在main()
功能上:
您需要检查该argc
值是否等于2
您的目的,然后才读入argv[1]
. 否则,如果程序在没有命令行参数(在这种情况下为 file_name)的情况下执行,则会发生无效的内存读取,如果您读取argv[1]
.
在read_file_and_show_the contents()
功能上:
如果到达文件末尾或读取最大字符并将其存储在字符数组中,则停止读取文件。
下面的程序将帮助您可视化:
#include <stdio.h>
/*Max number of characters to be read/write from file*/
#define MAX_CHAR_FOR_FILE_OPERATION 1000000
int read_and_show_the_file(char *filename)
{
FILE *fp;
char text[MAX_CHAR_FOR_FILE_OPERATION];
int i;
fp = fopen(filename, "r");
if(fp == NULL)
{
printf("File Pointer is invalid\n");
return -1;
}
//Ensure array write starts from beginning
i = 0;
//Read over file contents until either EOF is reached or maximum characters is read and store in character array
while( (fgets(&text[i++],sizeof(char)+1,fp) != NULL) && (i<MAX_CHAR_FOR_FILE_OPERATION) ) ;
//Ensure array read starts from beginning
i = 0;
while((text[i] != '\0') && (i<MAX_CHAR_FOR_FILE_OPERATION) )
{
printf("%c",text[i++]);
}
fclose(fp);
return 0;
}
int main(int argc, char *argv[])
{
if(argc != 2)
{
printf("Execute the program along with file name to be read and printed. \n\
\rFormat : \"%s <file-name>\"\n",argv[0]);
return -1;
}
char *filename = argv[1];
if( (read_and_show_the_file(filename)) == 0)
{
printf("File Read and Print to stdout is successful\n");
}
return 0;
}