c - 将文件 'filename' 读入字符缓冲区 'text'

标签 c bash shell command

我想知道如何从 Bash shell 的命令行运行此 C 代码?

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

/* Size of character buffer to read in a file. */
#define BUFFSIZE 1000000

/* Read file 'filename' into character buffer 'text'.*/

long read_file(char *filename, char *text ) {
FILE *fp   = fopen(filename, "r");
   long  size = 0; // Number of characters read.
   len  = 0;

if (fp == NULL) {
    fprintf(stderr, 
            "Error could not open file: %s\n", 
            strerror(errno));
    return -1;
}

/* Go to the end of the file. */
if (fseek(fp, 0L, SEEK_END) == 0) {
    /* Get the size of the file. */
    size = ftell(fp);
    if (size == -1) {
        fprintf(stderr, 
                "Error could not open file: %s\n",
                 strerror(errno));
        return -1;
    }

    /* Go back to the start of the file. */
    if (fseek(fp, 0L, SEEK_SET) != 0) {
        fprintf(stderr, 
                "Error rewinding to start of file: %s\n",
                 strerror(errno));
        return -1;
    }

    /* Read the entire file into memory. */
    len = fread(text, sizeof(char), (size_t)size, fp);
    if (len == 0) {
        fprintf(stderr, 
                "Error reading file into memory: %s\n", 
                 strerror(errno));
        return -1;
    } else {
       text[++len] = '\0'; /* Add a null-terminator. */
    }
}
(void)fclose(fp);
return size;
}

这就是文件中的所有代码,只是不确定我使用的命令,因为我已经使用过: chmod +x filename 使其可运行,然后我输入 ./filename 来运行,但只是收到错误消息,所以有我做错了什么,我只是不知道那是什么

最佳答案

你的代码编译了吗?尝试gcc <file.c> -o <outputName>

关于c - 将文件 'filename' 读入字符缓冲区 'text',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20657938/

相关文章:

bash - 查找和替换文件中的单词

linux - 如果目标文件不存在,如何退出 shell 脚本?

c - 数组下标的无效类型 'int*[__complex__ int]'

c++ - 数组中的订单号

java - 有没有办法用 JNI 设置 DirectByteBuffer 内存?

shell - 合并多个文本文件并删除重复项

shell - 如何在每行的开头添加数字?

c++ - 使用 Arduino 和 C++ 声明和写入数组的问题

arrays - 如何在 Bash 中将字符串拆分为数组?

git - 添加 Git Bash 别名