c - 将文本文件读入 c 字符串

标签 c

我正在开发一个 MediaPlayer 项目,该项目将播放文本文件而不是音频或视频。我的问题是如何显示 C 字符串数组中的字符串?例如,如果在文本文件中我有(不带引号):

**"This is only test"**

在我的程序中,我想一次显示一个单词,例如:

This
is
only
test

我该怎么做?这是到目前为止我的代码:

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

//Global variables
int position=0; //to set the player position
float rate = 1.0; //the rate of playback

void LoadFile(const char *fileName, char *text){
    FILE *ifp; //a file pointer for file read/write

    //opening the file
    ifp = fopen(fileName, "r");
    if(ifp == NULL){
            fprintf(stderr, "Can't open input file \"%s\"!\n",fileName);
            exit(1);
    }
    else{
            fgets(text,50,ifp); //getting the text from the file
    }
    //closing the file  
    fclose(ifp); 
}

void *Start();
void *Stop();
void Rewind();
void SeekTo(int byteOffset);
void setRate(float rate);

int main(void){
    int i = 0;
    char choice;
    char fileName[25];
    char lineOfText[50];    //holds the text inside the file
    printf("Please enter the file you want to open: ");
    scanf("%s", fileName);
    LoadFile(fileName,lineOfText);
    printf("%s",lineOfText);   //I will display the whole string

    return 0;
}

最佳答案

使用strtok函数

#include < stdio.h >

#include < string.h >

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  //printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

这段代码将给出输出

This
a
sample
string

要进一步了解,请参阅以下内容

http://www.cplusplus.com/reference/clibrary/cstring/strtok

关于c - 将文本文件读入 c 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10856283/

相关文章:

C netbeans错误

返回 void 的函数 g 可以返回 f() 吗? f 何时返回 void?

c - 在 C 中读取 PGM 图像(未正确读取文件)

c - C中的静态分配邻接矩阵图

c++ - 将 C++ 代码放入 C 时未定义对 `function()' 的引用

c - Padding - 加密算法

c++ - 使用哪个编辑器?用于编码 c/c++

c - NULL 检查单个 if 语句中的嵌套指针

java - 混合 C/Java OSGi 平台

使用链接列表创建地址簿