首页 > 解决方案 > 如何在 cabal 项目中导入文本文件?

问题描述

在 app/Main.hs 中,我想打开一个文本文件“foo.txt”。我知道如何在普通的 Haskell 程序中打开文本文件。在我的阴谋集团项目中,

import System.IO

Main = do
    contents <- readFile "foo.txt"
    print $ Main.lex contents
    return contents


type Keyword = String
lex :: String -> [Keyword]
lex "" = []
lex x = words x

给出错误

openFile:不存在(没有这样的文件或目录)

我需要更改我的 cabal 文件或文件路径或位置才能打开文件?我试过把它放在输出二进制文件旁边,但这也不起作用。

这是我的阴谋集团文件:

-- This file has been generated from package.yaml by hpack version 0.28.2.
--
-- see: https://github.com/sol/hpack
--
-- hash: baf2fc7e230f4b4937dfd918a13fefb55b66c7a4468b24d0e3e90cad675b26d5

name:           CCompiler
version:        0.1.0.0
description:    Please see the README on GitHub at <https://github.com/githubuser/CCompiler#readme>
homepage:       https://github.com/githubuser/CCompiler#readme
bug-reports:    https://github.com/githubuser/CCompiler/issues
author:         Author name here
maintainer:     example@example.com
copyright:      2018 Author name here
license:        BSD3
license-file:   LICENSE
build-type:     Simple
cabal-version:  >= 1.10
extra-source-files:
    ChangeLog.md
    README.md

source-repository head
  type: git
  location: https://github.com/githubuser/CCompiler

library
  exposed-modules:
      Lib
  other-modules:
      Paths_CCompiler
  hs-source-dirs:
      src
  build-depends:
      base >=4.7 && <5
  default-language: Haskell2010

executable CCompiler-exe
  main-is: Main.hs
  other-modules:
      Paths_CCompiler
  hs-source-dirs:
      app
  ghc-options: -threaded -rtsopts -with-rtsopts=-N
  build-depends:
      CCompiler
    , base >=4.7 && <5
  default-language: Haskell2010

test-suite CCompiler-test
  type: exitcode-stdio-1.0
  main-is: Spec.hs
  other-modules:
      Paths_CCompiler
  hs-source-dirs:
      test
  ghc-options: -threaded -rtsopts -with-rtsopts=-N
  build-depends:
      CCompiler
    , base >=4.7 && <5
  default-language: Haskell2010

标签: haskellcabal

解决方案


添加

data-dir: data

在 cabal 文件的顶部。

在 src 和 app 旁边创建目录“data”,并将所有文件放在那里。

确保你的 cabal 文件也有这一行

other-modules:
  Paths_CCompiler

使用您的项目名称而不是 CCompiler。

我的主要功能现在是这个

module Main where

import Lib
import System.IO
import Paths_CCompiler

main = do
    filepath <- getDataFileName "return_2.c"
    contents <- readFile filepath
    print $ Lib.lex contents
    return contents

感谢这篇博文


推荐阅读