我是C语言的新手,对学习这种语言感到非常沮丧。当前,我正在尝试编写一个程序,该程序读取程序文本文件,读取并打印所有字符串文字,并在单独的行中分别标记。除了一个障碍,我大部分都拥有。在文本文件中有一行,例如:(..text ..)。我需要能够搜索,阅读和打印所有文本,该文本在其自己的行上的括号内。到目前为止,我有一个想法:
#define KEY 32
#define BUFFER_SIZE 500
FILE *fp, *fp2;
int main()
{
char ch, buffer[BUFFER_SIZE], operators[] = "+-*%=", separators[] = "(){}[]<>,";
char *pus;
char source[200 + 1];
int i, j = 0, k = 0;
char *words = NULL, *word = NULL, c;
fp = fopen("main.txt", "r");
fp2 = fopen ("mynewfile.txt","w") ;
while ((ch = fgetc(fp)) != EOF)
{
// pus[k++] = ch;
if( ch == '(')
{
for ( k = 0;, k < 20, K++){
buffer[k] = ch;
buffer[k] = '\0';
}
printf("%s\n", buffer)
}
....
文本文件是这样的:
#include <stdio.h>
int main(int argc, char **argv)
{
for (int i = 0; i < argc; ++i)
{
printf("argv[%d]: %s\n", i, argv[i]);
}
}
到目前为止,我已经能够逐字符读取char并将其放入缓冲区。但是这个想法是行不通的,我很沮丧。我试过用strcopy()和strstok进行尝试,但是它们都使用char数组。任何想法将不胜感激谢谢。
最好的最佳方法很可能是将fgets()与文件一起使用,以字符串(char数组)的形式读取每一行,然后分隔该字符串。请参见下面的简短示例:
char buffer[BUFFER_SIZE];
int current_line = 0;
//Continually read in lines until nothing is left...
while(fgets(buffer, BUFFER_SIZE - 1, fp) != NULL)
{
//Line from file is now in buffer. We can delimit it.
char copy[BUFFER_SIZE];
//Copy as strtok will overwrite a string.
strcpy(copy, buffer);
printf("Line: %d - %s", current_line, buffer); //Print the line.
char * found = strtok(copy, separators); //Will delmit based on the separators.
while(found != NULL)
{
printf("%s", found);
found = strtok(NULL, separators);
}
current_line++;
}
strtok将返回一个char指针,该指针指向首次出现定界符的位置。它将用空终止符替换定界符,从而生成“新”字符串。我们可以将NULL传递给strtok,以告诉它从中断处继续执行。使用此方法,我们可以基于多个定界符从文件逐行解析。您可以保存这些单独的字符串或进一步评估它们。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句