C语言 如何从文件中读取字符直到空格并将其存储为一个字符串(c)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33968157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read characters from a file until a space and store that as one string (c)?
提问by MariaCodesOK
I need to read all the information from a line in a file before a space and store it as a string, how do I do that?
我需要在空格之前读取文件中一行中的所有信息并将其存储为字符串,我该怎么做?
File example:
文件示例:
Biology A 4.0
Tennis B 1.0
etc (I need the letter and number later and I know how to store them fine, just the dang string is giving me trouble)
等(我稍后需要字母和数字,我知道如何妥善保存它们,只是 dang 字符串给我带来了麻烦)
So far I have
到目前为止我有
int main (void)
{
FILE* grades;
char className[10];
char currChar;
int i = 0;
grades = fopen("grades.txt", "r");
if (fgetc(grades) != ' ')
{
currChar = fgetc(grades);
className[i] = currChar;
i++;
}
/* what I want to happen here: if a character is not a space, it is
appended to className. I thought if i was the position in the array,
I could add in one character at a time
*/
printf("%s", className); // check to make sure it worked
}
what the result is: the symbol that looks like a ? in a hexagon
结果是:看起来像 的符号?在一个六边形
Thanks for any help, I'm open to trying other ways too. I tried using fgets with the length i equal to the number of characters before a space found in a previous while loop, but that printed the part directly after the area I wanted.
感谢您的帮助,我也愿意尝试其他方式。我尝试使用 fgets 的长度 i 等于在前一个 while 循环中找到的空格之前的字符数,但是在我想要的区域之后直接打印了该部分。
回答by loxxy
Why not just use fscanf?
为什么不直接使用fscanf?
Something like :
就像是 :
#include <stdio.h>
int main (void)
{
FILE* grades;
char className[10];
char grade;
float marks = 0;
grades = fopen("grades.txt", "r");
while(fscanf(grades,"%s %c %f", className, &grade, &marks)>0) {
printf("%s %c %f\n", className, grade, marks);
}
}
回答by David C. Rankin
There is nothing wrong with reading from a file up-to the first spacecharacter with fgetc, however, there are several problems with:
从文件中读取到第一个space字符没有任何问题fgetc,但是,有几个问题:
if (fgetc(grades) != ' ')
{
currChar = fgetc(grades);
className[i] = currChar;
i++;
}
When you call fgetc(grades) != ' ', a character is read from gradesand then the file-position-indicatoris advanced to the next character. So when you call fgetcinside the ifstatement, you read a character and then the file-position-indicatoris advanced in preparation for reading the next character. When you then call fgetcagain in the body of the if statement (currChar = fgetc(grades);), you read the secondcharacter in the file. It seems rather obvious from your question, that your intent was not to skip-a-characterand then begin reading with the next.
当您调用 时fgetc(grades) != ' ',将从中读取一个字符grades,然后文件位置指示器前进到下一个字符。因此,当您fgetc在if语句内部调用时,您读取一个字符,然后文件位置指示符前进以准备读取下一个字符。当您fgetc在 if 语句 ( currChar = fgetc(grades);)的主体中再次调用时,您将读取文件中的第二个字符。从您的问题中可以看出,您的意图不是跳过一个字符,然后从下一个字符开始阅读。
When you read input with any character-oriented-inputfunction (e.g. getchar, fgetc, etc.) there are three primary things you are responsible for: (1) insuring you do not attempt to write more characters to your storage variable than it will hold; (2) check for any sentinelor terminating character you wish to stop the read with; and (3) checking that you have not reached the end of the input stream.
当您使用任何面向字符的输入函数(例如getchar、fgetc等)读取输入时,您需要负责三件事: (1) 确保您不会尝试向存储变量写入更多字符;(2) 检查您希望停止读取的任何标记或终止字符;(3) 检查您是否还没有到达输入流的末尾。
Putting those pieces together you could do something like:
将这些部分放在一起,您可以执行以下操作:
#include <stdio.h>
#define MAXCN 10
int main (void)
{
FILE* grades = NULL; /* initialize variables */
char className[MAXCN] = {0};
int currChar = 0; /* currChar is an int */
int i = 0;
/* open and validate file */
if ((grades = fopen("grades.txt", "r")) == NULL) {
fprintf (stderr, "error: file open failed 'grades.txt'.\n");
return 1;
}
/* read from grades until 1st space */
while (i + 1 < MAXCN && ((currChar = fgetc (grades)) != ' ' &&
currChar != EOF)) {
className[i++] = currChar;
}
className[i] = 0; /* null-terminate */
printf("\n className: %s\n\n", className);
return 0;
}
Note:when you stop reading on any character, the next read will resume on the next character in the input stream. So you will need to empty any characters that remain (in the line, etc...) if you want to begin your read at any than other than the next character. Also note, when you open a file with fopen, you should validate that the open actually worked before proceeding to read from the file.
注意:当您停止读取任何字符时,下一次读取将在输入流中的下一个字符上恢复。因此,如果您想从下一个字符以外的任何字符开始阅读,则需要清空剩余的任何字符(在行中等)。另请注意,当您使用 打开文件时fopen,您应该在继续读取文件之前验证打开是否确实有效。
Input
输入
$ cat grades.txt
Homeroom grades are include below
Output
输出
$ ./bin/fgetc_grades
className: Homeroom
Hopefully this will help you get started, let me know if you have any additional questions.
希望这能帮助您入门,如果您有任何其他问题,请告诉我。

