gpt4 book ai didi

c - 意外标记附近出现语法错误 '('

转载 作者:行者123 更新时间:2023-11-30 16:19:29 24 4
gpt4 key购买 nike

作为初学者,我正在尝试编写一个简单的 C 程序来学习和执行“write”函数。

我正在尝试执行一个简单的 C 程序 simple_write.c

#include <unistd.h>
#include <stdlib.h>
int main()
{
if ((write(1, “Here is some data\n”, 18)) != 18)
write(2, “A write error has occurred on file descriptor 1\n”,46);
exit(0);
}

我还执行 chmod +x simple_write.c

但是当我执行 ./simple_write.c 时,它给我意外标记“(”附近的语法错误

无法弄清楚为什么会发生这种情况?

P.S:预期输出是:-

$ ./simple_write
Here is some data
$

最佳答案

你做到了

$ chmod +x simple_write.c
$ ./simple_write.c

当你应该做的时候

$ cc simple_write.c -o simple_write$ chmod +x simple_write                 # On second thought, you probably don’t need this.$ ./simple_write

In words: compile the program to create an executable simple_write(without .c) file, and then run that. What you did was attempt to execute your C source code fileas a shell script.

Notes:

  • The simple_write file will be a binary file. Do not look at it with tools meant for text files(e.g., cat, less, or text editors such as gedit).
  • cc is the historical name for the C compiler. If you get cc: not found (or something equivalent),try the command again with gcc (GNU C compiler). If that doesn’t work,

    • If you’re on a shared system (e.g., school or library),ask a system administrator how to compile a C program.
    • If you’re on your personal computer (i.e., you’re the administrator),you will need to install the compiler yourself (or get a friend to do it). There’s lots of guidance written about this; just search for it.
  • When you get to writing more complicated programs,you are going to want to use

    make simple_write

    其优点

    • 能够编排多步骤构建,这是复杂程序的典型特征,并且
    • 它知道在该系统上编译程序的标准方法(例如,它可能“知道”是使用 cc 还是 gcc)。

    事实上,您现在应该能够使用上面的命令。这可能(或可能不会)简化您的生活。

<小时/>

附注现在这个问题出现在 Stack Overflow 上,我可以谈论它的编程方面。在我看来它应该编译,但是

  • 第一个 write 行的括号数量超出了需要。

    if (write(1, "Here is some data\n", 18) != 18)

    应该可以。

  • 在第二个 write 行中,我计算该字符串的长度为 48 个字符,而不是 46 个。
  • 顺便问一下,你知道如何让第一次write失败吗?那么第二个会执行吗?尝试一下

    ./simple_write>&-

关于c - 意外标记附近出现语法错误 '(',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55616443/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com