如何在cabal项目中导入文本文件?

时间:2018-11-24 12:14:05

标签: haskell 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

2 个答案:

答案 0 :(得分:2)

添加

data-dir: data

在阴谋文件的顶部。

在src和app旁边创建目录“ data”,然后将所有文件放在其中。

确保您的阴谋文件也有这一行

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

感谢this blog post

答案 1 :(得分:0)

我了解您的问题是关于在运行时查找文件,您要处理这些文件,而不将它们打包在一起。

有几种方法,如何在运行时查找未打包的文件。

要么添加命令行标志,然后使用要处理的文件的绝对路径调用可执行文件。

或实施文件选择器对话框,例如gi-gtk

或者不建议对相对路径进行硬编码,因为相对路径是相对于您进程的当前工作目录来解释的,取决于程序的启动方式,路径可能有所不同。

如果要确定程序在哪个当前工作目录中运行(如果以cabal run开头),则只需使用以下阴谋文件来进行一个小测试项目:

name: test2
build-type: Simple
cabal-version: >= 1.10
version: 0.0.0.1

executable test2
  hs-source-dirs: .
  main-is: test2.hs
  build-depends:
      base
    , directory

和以下test2.hs

module Main where

import System.Directory

main :: IO ()
main = do
  cwd <- getCurrentDirectory
  putStrLn cwd
相关问题