How to scan a string and write it in a file? - c

I want to scan a string that a user inputs, then write it into the file (file.txt), but this doesn't seem to work for some reason
int main()
{
FILE *stream;
stream = fopen("file.txt", "w");
char str[] = { '\0 ' };
scanf("%s", &str);
fprintf(stream, "%s.\n", str);
fclose(stream);
return(0);
}

try this, should work just fine.
It did for me so it should for you too.
#include <stdio.h>
#include <string.h>
int main()
{
FILE *stream;
stream = fopen("ceva.txt", "w");
if (stream == NULL) {
perror("Failed: ");
return 1;
}
char str[250];
scanf("%249s", str);
fprintf(stream, "%s.\n", str);
fclose(stream);
return 0;}

You must change scanf with fscanf

Related

C. Can't open a text file with fopen on Windows Vista

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.

copy a text file using c

What I want to do for now is have an input text file, load its content into a 2d array, perform something on it and then put it out into another file. Essential problem for me is keeping the original files' structure. This is my code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *ifp, *ofp;
char buffer[100];
int i, c;
ifp=fopen("test.in", "r");
ofp=fopen("test.out", "w");
while (!feof(ifp)){
if(fscanf(ifp, "%s", buffer) != 1)
break;
fprintf(ofp, "%s", buffer);
}
return 0;
}
my input:
aaa bb bbb
bbbbb bbbb aa
and output:
aaabbbbbbbbbbbbbbaa
Everything I tried for EOL or EOF recognition caused infinite loops. Performing anything with "%c" instead of "%s" resulted in worse outputs. Thanks in advance.
edit: I'm aware I can get the output to be words with spaces between them or have every word in a new line but I don't know how to get from here to final result.
Use "%c"
#include <stdio.h>
int main(void)
{
FILE *ifp, *ofp;
char buffer;
ifp=fopen("test.in", "r");
if(ifp==NULL)return 1;
ofp=fopen("test.out", "w");
if(ofp==NULL){
fclose(ifp);
return 1;
}
for(;;){
if(fscanf(ifp, "%c", &buffer) != 1)
break;
fprintf(ofp, "%c", buffer);
}
fclose(ifp);
fclose(ofp);
return 0;
}
or getc().
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *ifp, *ofp;
int buffer;
ifp=fopen("test.in", "r");
if(ifp==NULL)return 1;
ofp=fopen("test.out", "w");
if(ofp==NULL){
fclose(ifp);
return 1;
}
for(;;){
if((buffer = getc(ifp)) != EOF)
break;
putc(buffer, ofp);
}
fclose(ifp);
fclose(ofp);
return 0;
}
You won't neeed feof() because the functions used to read will detect EOF.
Also, don't forget to check if the files are successfully opened and to close the files opened.
Use getline function instead fscanf. Because fscanf can't read the full string which contain the space character
while ((read = getline(&line, &len, stream)) != -1)
{
printf("Retrieved line of length %zu :\n", read);
printf("%s", line);
}
See full detail about getline:
http://man7.org/linux/man-pages/man3/getline.3.html

Better way to convert string to integer

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.

Read from file in C and execute conditional logic

I am new to programming and have a few questions as to how to implement this idea.
I am looking to have a user enter their name/string of digits and if their name is on a list, to then execute a string of commands. I am not to sure how to impliment this, but with some gogle-ing I was able to come up with this code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char userName[10];
printf("\n\n\n\nPlease enter your name: ");
scanf_s("%s",userName); // userName should be verified/found inside the results.dat file
FILE *fp;
fp = fopen("results.dat", "r");
if (fp == NULL) {
printf("I couldn't open results.dat for writing.\n");
exit(0);
}
if (fp == John) {
//Dispence squence of pills for John
}
if (fp == Mary) {
//Dispence squence of pills for Mary
}
return 0;
}
I do not think I am using the if statement correctly. how can I do something like:
if (content in fp == john, execute/call another function)
Thanks in advance!
Try this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char userName[10];
char names[20];
printf("\n\n\n\nPlease enter your name: ");
scanf("%s",userName); // userName should be verified/found inside the results.dat file
FILE *fp;
fp = fopen("results.dat", "r");
if (fp == NULL) {
printf("I couldn't open results.dat for writing.\n");
exit(0);
}
while(fgets(names, 20, fp)) // fgets reads a line from the file
{
names[strlen(names)-1] = '\0'; // but it leaves the newline character "\n" , so the strings won't match
if(strcmp(names, userName) == 0) // if the value returned by strcmp is zero then string match
{
printf("Match found\n");
}
}
return 0;
}
fopen simply opens a file for reading and/or writing, to read the actual content of the file you need to use functions such as fgets, fscanf and so on.
Short example
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char* argv[])
{
char name[64];
char buffer[64];
printf ("Please enter your name: ");
file = fopen ("results.dat", "rw");
if (!file) {
printf ("Results.dat could not be opened.\n");
exit(-1);
}
if ( fgets (buffer, 64, file)) {
if (strcmp (buffer, "john")) {
printf ("Contents of file is john\n");
}
}
return 0;
}

reading a string from a file

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;
}

Resources