从文件中保存变量?
saving variables in line from file?
我正在尝试读取行并从中提取信息。例如,我的文字有;
abate terminar, hacer cesar
abated amainado, amplacado, mitigado
这是一本字典。
第一个词是英语,其余是西班牙语。我正在尝试将英文单词保存到一个变量中,然后将该行的其余部分保存到另一个变量中。我不知道该怎么做?我写了这段代码来读取所有文本文件并将其全部打印出来。
int main(int argc, const char * argv[]) {
char filename[] = "/Users/MyName/Desktop/span.rtf";
FILE *file = fopen ( filename, "r" );
if (file != NULL) {
char line [1000];
while(fgets(line,sizeof line,file)!= NULL) /* read a line from a file */ {
fprintf(stdout,"%s",line); }
fclose(file);
}
return 0;
}
这是一个很好的开始,使用 fgets()
读取整行然后进行解析是一个很好的方法。
接下来您需要考虑如何存储您的词典。一种方法可能是静态大小的结构数组:
struct {
char *english;
char *spanish;
} words[1000];
假设不超过 1000 个单词。
要存储每一行,只需找到第一个 space 字符并将其作为英语和西班牙语之间的分隔符:
size_t word_count = 0;
while(fgets(line, sizeof line, file) != NULL)
{
char * const sp = strchr(line, ' ');
if(sp != NULL)
{
*sp = '[=11=]';
while(isspace((unsigned char) *++sp))
;
if(isalpha((unsigned char) *sp)
{
words[word_count].english = strdup(line);
words[word_count++].spanish = strdup(sp);
}
}
}
类似的东西应该让你开始。这假设 strdup()
存在,如果你没有重新实现它是微不足道的。当然你应该添加代码来检查内存分配失败。
试试这个:
char english[256];
char spanish[256];
while(fscanf(file,"%[a-z]%*[ ]%[a-z, ]\n", english, spanish) != 0) {
fprintf(stdout, "English: %s\n Spanish: %s\n", english, spanish);
}
我正在尝试读取行并从中提取信息。例如,我的文字有;
abate terminar, hacer cesar
abated amainado, amplacado, mitigado
这是一本字典。 第一个词是英语,其余是西班牙语。我正在尝试将英文单词保存到一个变量中,然后将该行的其余部分保存到另一个变量中。我不知道该怎么做?我写了这段代码来读取所有文本文件并将其全部打印出来。
int main(int argc, const char * argv[]) {
char filename[] = "/Users/MyName/Desktop/span.rtf";
FILE *file = fopen ( filename, "r" );
if (file != NULL) {
char line [1000];
while(fgets(line,sizeof line,file)!= NULL) /* read a line from a file */ {
fprintf(stdout,"%s",line); }
fclose(file);
}
return 0;
}
这是一个很好的开始,使用 fgets()
读取整行然后进行解析是一个很好的方法。
接下来您需要考虑如何存储您的词典。一种方法可能是静态大小的结构数组:
struct {
char *english;
char *spanish;
} words[1000];
假设不超过 1000 个单词。
要存储每一行,只需找到第一个 space 字符并将其作为英语和西班牙语之间的分隔符:
size_t word_count = 0;
while(fgets(line, sizeof line, file) != NULL)
{
char * const sp = strchr(line, ' ');
if(sp != NULL)
{
*sp = '[=11=]';
while(isspace((unsigned char) *++sp))
;
if(isalpha((unsigned char) *sp)
{
words[word_count].english = strdup(line);
words[word_count++].spanish = strdup(sp);
}
}
}
类似的东西应该让你开始。这假设 strdup()
存在,如果你没有重新实现它是微不足道的。当然你应该添加代码来检查内存分配失败。
试试这个:
char english[256];
char spanish[256];
while(fscanf(file,"%[a-z]%*[ ]%[a-z, ]\n", english, spanish) != 0) {
fprintf(stdout, "English: %s\n Spanish: %s\n", english, spanish);
}