I wrote this code to read a variable in a .txt file, ignore the first character and convert into a integer.It works but looks dumb, is there a better way to do this? I'm using just one string here but it's supposed to work with four.
void read(char a[])
{
int i;
char a1[3];
for (i = 0; i<3; ++i){
a1[i]= a[i+1];
}
int b1 = atoi(a1);
}
int main()
{
FILE *file;
file = fopen( "file.txt", "r");
if (file == NULL) {
printf( "Arquivo nao encontrado\n");
}
char a[4];
fscanf(file, "%s\n",&a);
read(a);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char filename[] = "file.txt";
FILE *fp = fopen(filename, "r");
if (fp == 0)
{
fprintf(stderr, "Failed to open file %s for reading\n", filename);
return(EXIT_FAILURE);
}
int value;
if (fscanf(fp, "%*c%d", &value) != 1)
{
fprintf(stderr, "Failed to read integer value from file %s\n", filename);
fclose(fp);
return EXIT_FAILURE;
}
printf("Read %d\n", value);
fclose(fp);
return 0;
}
The %*c reads a single character but does not assign it. The * to suppress an assignment is a general mechanism in the scanf()
family of functions.
Untested code.
Related
I am trying to write these parameters in a file .txt, but when I open the file (even before that it shows me a warining about the encoding) it appers like a bug, full of ????, like this:
$�U�z�G��?xpto%�U\���(\�?xpto&�Uףp=
��?xpto'�UR���Q�?xpto(�U�������?xpto)�UH�z�G�?xpto*�U��(\���?xpto+�U>
ףp=�?xpto,�U���Q��?xpto-�U433333�?xpto
I've searched a lot about but as it is a specifically error, i cannot find nothing about it.
What is happening?
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
typedef struct
{
int age;
double height;
char name[64];
} Person;
void printPersonInfo(Person *p)
{
printf("Person: %s, %d, %f\n", p->name, p->age, p->height);
}
int main (int argc, char *argv[])
{
FILE *fp = NULL;
int i;
Person p = {35, 1.65, "xpto"};
/* Validate number of arguments */
if(argc != 2)
{
printf("USAGE: %s fileName\n", argv[0]);
return EXIT_FAILURE;
}
/* Open the file provided as argument */
errno = 0;
fp = fopen(argv[1], "w");
if(fp == NULL)
{
perror ("Error opening file!");
return EXIT_FAILURE;
}
/* Write 10 itens on a file */
for(i = 0 ; i < 10 ; i++)
{
p.age = p.age+1;
p.height = p.height+0.03;
fwrite(&p, sizeof(Person), 1, fp);
}
fclose(fp);
return EXIT_SUCCESS;
}
The fwrite function is writing the binary representation of the struct p to the file. If you want to write text, use fprintf:
fprintf(fp, "%d %f %s\n", p.age, p.height, p.name);
I wanted to learn how to use getc function in C so I wrote a little program that is supposed to give the first letter of a text file as an output.
Here's how it looks:
int main()
{
int character;
FILE *file;
file = fopen("file.txt", "r");
if(file == NULL)
printf("can't open\n");
character = getc(file);
printf("%c", character);
fclose(file);
return 0;
}
It fails to open the file.txt file and I can't figure out why. file.txt is in the same folder as my program's .exe file. I'm using Windows Vista.
Thanks in advance
This extracts the program's location from argv[0]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MYFILE "plik.txt"
int main(int argc, char *argv[]) {
char fname[_MAX_PATH+1];
int znak;
FILE *plik;
char *ptr;
strcpy(fname, argv[0]);
ptr = strrchr(fname, '\\');
if(ptr == NULL) {
strcpy(fname, MYFILE);
}
else {
strcpy(ptr+1, MYFILE);
}
plik = fopen(fname, "r");
if(plik == NULL) {
printf("Can't open %s\n", fname);
}
else {
znak = getc(plik);
printf("First char of %s is %c\n", fname, znak);
fclose(plik);
}
getchar();
return 0;
}
Try
if (plik == NULL) { perror("plik.txt"); exit(EXIT_FAILURE); }
for a better understanding of the cause of error.
I am trying to figure out why this is not printing, I am trying to print each letter from a text file that is inputted through command prompt, but I am just getting an empty output... What am I doing wrong, and why does this not work? I feel like this logically should work. Thanks.
int main(int argc, char *argv[]) {
FILE *fp;
int i;
for (i = 1; i < argc; i++) {
printf("%s\n", argv[i]);
fp = fopen(argv[i], "r");
while (!feof(fp)) {
puts(fp);
}
fclose(fp);
}
return 0;
}
You are attempting to print a file pointer:
puts(fp);
Read the manual of puts() -that's not what it takes.
To read char-by-char and print on the stdout, you can do:
int ch;
fp = fopen(argv[i], "r");
if (!fp) {
perror("fopen");
exit(1);
}
while((ch=fgetc(fp)) != EOF) {
putchar(ch);
}
flcose(fp);
Unless you are passing multiple file names as arguments, your outer loop doesn't make much sense.
Your program has multiple problems:
You do not test the return value of fopen(): the program invokes undefined behavior if any of the command line arguments cannot be opened as a stream for reading.
while(!feof(fp)) is incorrect. Read this: Why is “while ( !feof (file) )” always wrong?
puts(fp); is incorrect as fp is a FILE *, not a string. Use a loop to copy the file contents one byte at a time.
Here is a corrected version:
#include <errno.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
FILE *fp;
int i, c;
for (i = 1; i < argc; i++) {
fp = fopen(argv[i], "r");
if (fp == NULL) {
fprintf(stderr, "cannot open %s: %s\n", argv[i], strerror(errno));
} else {
printf("%s\n", argv[i]);
while ((c = getc(fp)) != EOF) {
putchar(c);
}
fclose(fp);
}
}
return 0;
}
int main(int argc, char *argv[]) {
FILE *fp;
int i;
char buff[128];
for (i = 1; i < argc; i++) {
printf("\n%s\n", argv[i]);
if(NULL == (fp = fopen(argv[i], "r"))){//check open file
perror("fopen");
continue;
}
while (fgets(buff, sizeof buff, fp)) {//read into buffer
fputs(buff, stdout);//print buffer (not add newline)
}
fclose(fp);
}
return 0;
}
1) I'm trying to open a file, read the mix data (ints, chars and strings) and store them into args.
1.1) so in the sample.txt is a total of 13 (excluding args[0])
2) Need to read a file from terminal "./myprog.c < sample.txt"
Heres my code and have no idea where i went wrong:
sample.txt:
123 213 110 90 1
hello my friend
boo bleh
a b c
myprog.c:
#include <stdio.h>
int main()
{
int i = 1;
FILE *fstin=fopen(argv[0], "r"); //open the file
if (fstin == NULL) {
puts("Couldn't fopen...");
return -1;
}
//Getting all the inputs from file
while ((fscanf(fstin, "%d", argv[i])) != EOF){
i++;
}
fclose(fstin);
for (i=0; i<10; i++) {
printf("%d\n",argv[i]);
}
return 0;
}
Any help is greatly appreciated!
PS: Would like if anyone could post their complete solution? Will upload unto this post and let everyone have a review of this problem
PPS: Please excuse the poor level of coding as I am a beginner and completely new to C.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int ac, char *av[]){
int i, argc=0;
char **argv=NULL, data[16];
FILE *fstin = stdin;
if(ac == 2){
if(NULL==(fstin = fopen(av[1], "r"))){
puts("Couldn't fopen...");
return -1;
}
}
while (1==fscanf(fstin, "%15s", data)){
argv = realloc(argv, (argc+1)*sizeof(char*));
argv[argc] = malloc(strlen(data)+1);
strcpy(argv[argc++], data);
}
if(ac == 2)
fclose(fstin);
for (i=0; i<argc; ++i) {
printf("%s\n", argv[i]);
}
//deallocate
return 0;
}
You are making mistake at 2nd point where you divert your file to other file which is wrong. Actually you need to first compile and need to make executable.
gcc -o my_prog ./myprog.c -Wall
You need to execute this program as below to read file from c program:
./my_prog ./sample.txt
As you are new to C programming first go to man pages related to file operations.
Solution:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
//If command line argument is not inserted then stop operation
if (2 != argc) {
printf("Invalid number of arguments : %d\n", argc);
return -1;
}
int size = 0, ret = 0;
char *data = NULL;
FILE *fp = NULL;
//Open file in read mode given from command line argument
if (NULL != (fp = fopen(argv[1], "r")))
{
//Find size of file
fseek(fp, 0L, SEEK_END);
size = ftell(fp);
fseek(fp, 0L, SEEK_SET);
//if file is empty no need to read it.
if (size > 0)
{
//Data pointer which contains file information
data = (char *) calloc(sizeof(char), size);
if (NULL != data)
{
//Read whole file in one statement
fread(data, sizeof(char), size, fp);
printf("File %s is readed successfully\n", argv[1]);
printf("Data:\n");
printf("%s\n", data);
free(data); data = NULL;
}
else
{
perror("memory allocation failed\n");
ret = -1;
}
}
else
{
printf("File %s is empty\n", argv[1]);
}
fclose(fp); fp = NULL;
}
else
{
perror("File open failed\n");
ret = -1;
}
return ret;
}
Now Test it on your setup and if any query please post comments.
I have one text file. I have to read one string from the text file. I am using c code. can any body help ?
Use fgets to read string from files in 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.
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>
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;
}
The return value is 1 if all went well, 0 on error.
Since this uses a plain fgets(), it will retain the '\n' line feed at the end of the line (if present).
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)] = '\0';
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 */
}
This is a Simple way to get the string from file.
#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;
}