![](/img/trans.png)
[英]How can I read a known number of strings of unknown size from a .txt file and store each line in a line of a matrix (in C)?
[英]C language help:How to store strings from a .txt file into a character array? This .txt file is read from a command line argument btw.
我需要创建一个程序,该程序将使用命令行参数读取.txt文件,然后在该txt文件中加密消息。
我使用指针打开txt文件,并成功打开它。 但是我需要将消息(由许多段落组成)存储到单个字符数组中,以便可以开始加密。
例如,如果消息是:我爱狗
我想将该消息存储到一个字符数组中,例如:
char word[5000];
char word[0] = I;
char word[1] = l;
char word[2] = o;
etc....
我尝试使用for循环将消息存储到单个字符数组中,但是当我尝试打印出该数组时,它不会显示在命令行中。
如何将.txt文件中的消息存储到单个字符数组中?
这是我的代码:
int main(int argc, char*argv[])
{
int a;
printf("The number of arguements is :%d \n", argc);
for(a=0; a<argc; a++)
{
printf("argc %d is %s \n",a, argv[a]);
}
//此部分使用文件指针从文本文件中读取然后显示它
printf("\n");
char * fname= argv[1];
FILE *fptr= fopen(fname, "r");
char word[5000];
int c;
if (fptr==0)
{
printf("Could not open file\n");
}else
{
printf("FILE opened successfully \n");
}
while (fgets(word, 5000, fptr) !=NULL)
{
printf("%s \n", word);
}
fclose(fptr);
while循环使用旨在逐行读取的fget。 如果您想要一个代表文件字节的字符数组,请使用fread。 首先,您需要知道文件的大小; 为此使用stat或fstat。
#include <stat.h>
struct stat statbuf;
int FS;
char* buffer
if (fstat(fileno(fptr),&statbuf)){
... handle error
}
FS = statbuf.st_size;
然后,对于FS中现在的文件大小,分配一些字节
buffer = (char*) malloc(FS)
然后阅读内容
fread(buffer, 1, FS, fptr)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.