繁体   English   中英

试图从C中的txt文件中获取字符串

[英]Trying to get the strings out a txt file in c

由于某种原因,我在行后得到了理解:

currentString[i] = *currentChar;

此代码用于从文件中收集所有字符,直到遇到字符';',然后将它们放入字符串中。 有人知道这是怎么回事吗? 谢谢! 这是所有代码:

char currentString[100] = { 0 };
char *currentChar;

//opening the input file
FILE *input = fopen("input.txt", "r");
//if the file doesn't exist, the pointer will contain NULL
if (input == NULL)
{
    exit(1);
}

//assigning the start of the input file adress to currentChar
currentChar = input;

//while the current character isn't the last character of the input file
while (currentChar < input + strlen(input) + 1)
{
    while (currentChar != ';')
    {
        currentString[i] = *currentChar;
        printf("%c", *currentChar);
        currentChar = currentChar + 1*sizeof(char);
        i++;
    }
}

input是指向不透明FILE类型的指针,而不是您似乎假定的指向文件内容的指针。 这意味着您不能直接通过指针访问文件的内容。 相反,您需要将input传递给从文件读取输入的函数,例如fgetsgetcfscanf

您根本没有从文件中读取内容。 这个:

currentChar = input;

input指向的FILE对象的地址分配给currentChar 这也是类型不匹配,因为您正在将FILE *分配给char * 您也不能在input使用strlen ,因为它不是char * 您应该已经收到很多关于这些的编译器警告。

要从文件读取字符,请使用fgetc函数:

int currentChar = fgetc(input);

//while the current character isn't the last character of the input file or a ';'
while (currentChar != EOF && currentChar != ';')
    currentString[i] = currentChar;
    printf("%c", currentChar);
    currentChar = fgetc(input);
    i++;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM