c - 使用 strtok 和数组从文件读取并写入另一个文件
问题描述
我有一个关于使用该strtok
函数的 C 语言的项目。我正在使用 while 循环读取文件,并且我正在使用分隔符“”(空格)不断地对句子中的单词进行标记。当我阅读文件时,如果我在文件 A 中遇到我用 if 语句指定的单词,我必须将特定的行写入文件 B(宏处理器的扩展)。问题是,每当我尝试从文件 A 中读取并分别写入文件 BI 中的每一行时,我只会从文件 A 中获取最后一行,我需要检查每一行并逐一写入。
while(fgets(str,100,fp) != NULL){
fgets(str,100,fp);
if (str[0] == '@')
{
char *array[300];
char *p = strtok (str," \n");
while (p != NULL) //tokenize the words, and save into array
{
array[i++] = p;
p = strtok (NULL, " ");
}
if (!strcmp(array[0],"@def")) // if the very first word encountered in the line is @def, write the words below into the file B
{
fprintf(fptr2, "define %s %s\n",array[1],array[2]);
} //defining a global variable
else if (!strcmp(array[0],"@mat"))// if the very first word encountered in the line is @mat, write the words below into the file B
{
fprintf(fptr2, "int %s[%s][%s]\n",array[1],array[2],array[3]);
}//defining a 2 dimensional array with dimensions MxN
}
}
如果文件 A 包含以下行:
@mat A N M
@def N 100
文件 B 将仅写入此行:
define N 100
但它应该有
int A[N][M]
define N 100
同样,如果文件 A 包含以下行:
@def N 100
@mat A N M
文件 B 将在此处写入这一行:
int A[N][M]
但它应该有
define N 100
int A[N][M]
解决方案
推荐阅读
- angular - Angular 7 Hot Reload 挂起
- mysql - SQL 语句混乱,时间戳返回不准确的结果
- elasticsearch - 有没有办法在 kibana/elasticsearch 中进行主索引?
- python - 阅读文档本地安装:Celery ValueError: signal only works in main thread
- json - 如何从 Swfit 中的复杂 JSON (Google Books API) 中仅获取某些值
- linux - 使用 sys_brk 在 Linux 上的 Intel Assembly 中进行动态内存分配
- amazon-web-services - 在 docker 中找不到 aws 命令
- css - 为什么范围样式没有加载到 nuxt 页面中?
- flutter - Flutter:TextFormField 上的 onTap 仅在热重载后触发
- svelte - 在工兵中切换布局?