[英]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.
I need to create a program that will read in a .txt file using the command line arguments and then encrypt the message in that txt file. 我需要创建一个程序,该程序将使用命令行参数读取.txt文件,然后在该txt文件中加密消息。
I used pointer to open the txt file and I opened it successfully. 我使用指针打开txt文件,并成功打开它。 But I need to store the message (consists of many paragraphs) into an array of single characters so that I can start my encryption.
但是我需要将消息(由许多段落组成)存储到单个字符数组中,以便可以开始加密。
For example, if the message is: I love dogs 例如,如果消息是:我爱狗
I want to store that message into an array of characters such as: 我想将该消息存储到一个字符数组中,例如:
char word[5000];
char word[0] = I;
char word[1] = l;
char word[2] = o;
etc....
I tried to use a for loop to store the message into single character array, but when I tried to print out the array it does not show on my command line. 我尝试使用for循环将消息存储到单个字符数组中,但是当我尝试打印出该数组时,它不会显示在命令行中。
How can I store the message from the .txt file into a single character array? 如何将.txt文件中的消息存储到单个字符数组中?
this is my code: 这是我的代码:
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]);
}
//This section uses file pointer to read from a text file and then display it //此部分使用文件指针从文本文件中读取然后显示它
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);
Your while loop uses fgets that is intended to read line by line. while循环使用旨在逐行读取的fget。 If you want an array of characters that represents the bytes of the file, use fread.
如果您想要一个代表文件字节的字符数组,请使用fread。 First you'll need to know how big the file is;
首先,您需要知道文件的大小; use stat or fstat for that.
为此使用stat或fstat。
#include <stat.h>
struct stat statbuf;
int FS;
char* buffer
if (fstat(fileno(fptr),&statbuf)){
... handle error
}
FS = statbuf.st_size;
Then, for the file size now in FS, allocate some bytes 然后,对于FS中现在的文件大小,分配一些字节
buffer = (char*) malloc(FS)
Then read the contents 然后阅读内容
fread(buffer, 1, FS, fptr)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.