1

我收到一条令人困惑的错误消息。我在 Windows XP 32 位上运行 MinGW。当我尝试编译以下代码时,我收到一条错误消息“./hello.c: line 4: Syntax error near unexpected token '('". Line 4 is at int main(...), I can't找出什么意外标记是“靠近'('”。我尝试使用 int main(void),但我得到了相同的消息。但是,如果我在没有“char string...”和“data = fputs(...)" 并从给定的文本文件中读取它,它编译没有问题。

我想要完成的是从文件名由外部源给出的文件中读取,即 php.ini 文件。最终,我将使用我制作的解析器将其放入一个 Apache 模块中,因此是来自 php 的调用,但我想在进入该部分之前构建一些模板代码以供使用。

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
    FILE *fp;
    //char string = "JD";    commented out
    char data;
    //printf("Type in your filename:   "); also commented out
    //scanf("%s", &argv);  also commented out

    if(argc >= 2)
    {
        fp = fopen("sample.txt", "r"); //switched to reading a given file
    }
    while((data = getchar()) != EOF)
    {
        fgets(data, sizeof(data), fp);
        // data = fputs(string, fp);
    }

    if (fp==NULL) /* error opening file returns NULL */
    {
        printf("Could not open player file!\n"); /* error message */
        return 1; /* exit with failure */
    }
    /* while we're not at end of file */
    while (fgets(data, sizeof(string), fp) != NULL)
    {
        printf(data); /* print the string */
    }

    fclose(fp); /* close the file */
    return 0; /* success */
}

好的,我尝试编写一个简单的“Hello World”程序,但我仍然收到相同的错误消息,这让我认为错误消息根本不是由我的代码引起的。

#include <stdio.h>

int main(void) //still getting a syntax error before unexpected token '('
{
    printf("Hello, world!");
    return 0;
}
4

4 回答 4

0

你的线

int main (int argc, char *argv)

是错的。肯定是

int main (int argc, char *argv[])

或者

int main (int argc, char **argv) //less common, though

还有你的线

char string = "JD";

应该

const char *string = "JD";

另外,我不明白

scanf("%s", &argv);

你为什么要读INTO argv的东西?

于 2013-08-16T09:29:42.237 回答
0
#include <stdio.h>
#include <stdlib.h>

#define MAXLINE 1024  // a normal buffer size for fgets
int main (int argc, char *argv[])
{
    FILE *fp;
    //char string = "JD";
    //char data;
    char buffer[MAXLINE];
    if(argc != 2)
    {printf("usage : ./a.out <filename>\n"); return -1;}

    if((fp = fopen(argv[1],"r+")) == NULL)
    {printf("open file %s error\n",argv[1]); return -1;}

   /*
    while((data = getchar()) != EOF)
    {
        fgets(data, sizeof(data), fp);
        data = fputs(string, fp);
    }*/      //I don't understand this part .


    /* while we're not at end of file */
    while (fgets(buffer,MAXLINE , fp) != NULL)
    {
        printf("%s\n",buffer); /* print the string */
    }

    fclose(fp); /* close the file */
    return 0; /* success */
}
于 2013-08-16T10:18:18.030 回答
0

让我的电脑休息一段时间后,我尝试重新编译没有该fgets()功能的不同源代码,并且它们已经正确编译。fgets()正如alk所指出的,我猜测该函数是由于函数引发的未定义行为而导致我的语法错误的原因,因为没有它的任何代码现在都在编译时没有错误,所以我正在考虑回答这个问题。

于 2013-08-17T15:41:29.200 回答
0

问题显然是在 hash ( # ) 之后和include之前缺少空间。
在我添加空间之后,它就像一个魅力。

(我知道这个帖子有点老了,但谷歌把我带到这里是因为我遇到了同样的问题,并试图找出问题所在,所以也许这会对其他人有所帮助。)

于 2014-06-19T22:12:19.997 回答