C语言 从文件中读取字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5153677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
reading a string from a file
提问by user556761
I have one text file. I have to read one string from the text file. I am using c code. can any body help ?
我有一个文本文件。我必须从文本文件中读取一个字符串。我正在使用 c 代码。任何身体都可以帮忙吗?
回答by Pablo Santa Cruz
Use fgetsto read string from files in C.
用于fgets从C 中的文件读取字符串。
Something like:
就像是:
#include <stdio.h>
#define BUZZ_SIZE 1024
int main(int argc, char **argv)
{
char buff[BUZZ_SIZE];
FILE *f = fopen("f.txt", "r");
fgets(buff, BUZZ_SIZE, f);
printf("String read: %s\n", buff);
fclose(f);
return 0;
}
Security checks avoided for simplicity.
为简单起见,避免了安全检查。
回答by Shebin
void read_file(char string[60])
{
FILE *fp;
char filename[20];
printf("File to open: \n", &filename );
gets(filename);
fp = fopen(filename, "r"); /* open file for input */
if (fp) /* If no error occurred while opening file */
{ /* input the data from the file. */
fgets(string, 60, fp); /* read the name from the file */
string[strlen(string)] = '#include <stdio.h>
#include <stdlib.h>
int read_line(FILE *in, char *buffer, size_t max)
{
return fgets(buffer, max, in) == buffer;
}
int main(void)
{
FILE *in;
if((in = fopen("foo.txt", "rt")) != NULL)
{
char line[256];
if(read_line(in, line, sizeof line))
printf("read '%s' OK", line);
else
printf("read error\n");
fclose(in);
}
return EXIT_SUCCESS;
}
';
printf("The name read from the file is %s.\n", string );
}
else /* If error occurred, display message. */
{
printf("An error occurred while opening the file.\n");
}
fclose(fp); /* close the input file */
}
回答by unwind
This should work, it will read a whole line (it's not quite clear what you mean by "string"):
这应该有效,它会读取整行(“字符串”的意思不是很清楚):
#include<stdio.h>
#include<stdlib.h>
#define SIZE 2048
int main(){
char read_el[SIZE];
FILE *fp=fopen("Sample.txt", "r");
if(fp == NULL){
printf("File Opening Error!!");
}
while (fgets(read_el, SIZE, fp) != NULL)
printf(" %s ", read_el);
fclose(fp);
return 0;
}
The return value is 1 if all went well, 0 on error.
如果一切顺利,返回值为 1,错误时返回 0。
Since this uses a plain fgets(), it will retain the '\n' line feed at the end of the line (if present).
由于这使用了普通的 fgets(),因此它将在行尾保留 '\n' 换行符(如果存在)。
回答by Manthan Solanki
This is a Simple way to get the string from file.
这是从文件中获取字符串的简单方法。
##代码##
