张晴朗 发表于 2022-7-14 13:31:08

课后作业第一节,求大神指点哪里出问题了

求大神解答,第一节课后作业原封不动复制的代码,运行后却出现语法错误,这是怎么回事。是不是我安装的centos有问题缺少什么函数?




原代码:#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>

#define MAX 256

long total;

int countLines(const char *filename);
int isCode(const char *filename);
void findAllDirs(const char *path);

int countLines(const char *filename)
{
      FILE *fp;
      int count = 0;
      int temp;

      if ((fp = fopen(filename, "r")) == NULL)
      {
                fprintf(stderr, "Can not open the file: %s\n", filename);
                return 0;
      }

      while ((temp = fgetc(fp)) != EOF)
      {
                if (temp == '\n')
                {
                        count++;
                }
      }

      fclose(fp);

      return count;
}

int isCode(const char *filename)
{
      int length;

      length = strlen(filename);
      
      if (!strcmp(filename + (length - 2), ".c"))
      {
                return 1;
      }
      else
      {
                return 0;
      }
}

void findAllDirs(const char *path)
{
      DIR *dp;
      struct dirent *entry;
      struct stat statbuf;

      if ((dp = opendir(path)) == NULL)
      {
                fprintf(stderr, "The path %s is wrong!\n", path);
                return;
      }

      chdir(path);
      while ((entry = readdir(dp)) != NULL)
      {
                lstat(entry->d_name, &statbuf);

                if (!strcmp(".", entry->d_name) || !strcmp("..", entry->d_name))
                        continue;

                if (S_ISDIR(statbuf.st_mode))
                {
                        findAllDirs(entry->d_name);
                }
                else
                {
                        if (isCode(entry->d_name))
                        {
                              total += countLines(entry->d_name);
                        }
                }
      }

      chdir("..");
      closedir(dp);
}

int main()
{
      char path = ".";

      printf("计算中...\n");

      findAllDirs(path);

      printf("目前你总共写了 %ld 行代码!\n\n", total);

      return 0;
}

henkuderen 发表于 2022-7-14 13:35:16

你这边是直接在终端输入你的代码了,然而代码是需要写在.c或者.cpp文件中再通过终端执行指令编译运行的。建议你还是再一步一步跟着视频来吧。

临时号 发表于 2022-7-14 15:16:20

谁让你在终端写C语言代码的,在终端里只能写shell
写C语言程序的方法:
在终端内输入vi test.c然后回车
按i键
输入C语言代码
按esc键
再输入:wq然后回车
在终端内输入gcc test.c -o test然后回车
再在终端内输入./test然后回车

ExiaGN001 发表于 2022-7-14 18:41:31

别在CMD里直接写代码啊
搞个编译器吧

张晴朗 发表于 2022-7-15 09:49:42

ExiaGN001 发表于 2022-7-14 18:41
别在CMD里直接写代码啊
搞个编译器吧

安装centos编译器了,不知道怎么调出来

做最好的自己520 发表于 2022-7-15 15:07:15

跟着视频一步一步运行代码   下次建议贴个图片吧

ExiaGN001 发表于 2022-7-15 20:11:02

张晴朗 发表于 2022-7-15 09:49
安装centos编译器了,不知道怎么调出来

linux系这边我也不是特别懂啊
页: [1]
查看完整版本: 课后作业第一节,求大神指点哪里出问题了