not able to open file with fopen function in c using Turbo C - turbo-c

I am using Turbo C. for below program when I debug code I always get the "Cannot read file" on output window. Input path of file is given as "PR1.txt" and same file present on C: as well.
#include "stdio.h"
#include "stdlib.h"
void main(void)
{
FILE *fp;
int value;
char ch;
fp = fopen("PR1.txt","w");
if(!fp)
{
printf("Cannot read file");
}
else
{
printf ("\n entr char to wrtite in file ::");
scanf("%c",&value);
fputc(ch,fp);
fclose(fp);
fp=fopen("PR1.c","r") ;
value=getc(fp);
printf("\n The result is= %d",value);
fclose(fp);
getch();
}

By default, your program will try to find the file in the location where you are executing the program. So make sure your data file is in the same folder or put the full path with the filename.

Related

fread() from binary file then printf streamed string - not working

C Lang Newb: My goal: Using a character stream using getchar() into an array and write array to a binary file, and then retrieve binary file into array and output string on console. I was successful with all parts except the output to console.
Call to function:
if (c == '6')
loadDoc();
Write file function:
int saveDoc(char document[MAXSIZE], int size){
FILE *f;
f = fopen("document.bin", "wb");
if (!f) {
printf("Error during writing to file !\n");
}
else{
fwrite(&document, sizeof(document), size, f);
fclose(f);
}
return 0;
}
Read file function:
char loadDoc(){
char buffer[1000];
FILE *f;
f = fopen("document.bin", "rb");
if (!f) {
printf("Error during reading file !\n");
}
else {
printf("Size of buffer: %d\n", sizeof(buffer));
fread(&buffer, sizeof(buffer), 1, f);
printf("File cpntents: \n %s\n", buffer);
fclose(f);
}
return 0;
}
Output:
********************
1) Start New Document:
2) View Document:
3) Edit Document:
4) Delete Document:
5) Save Document:
6) Load Document:
7) Exit
********************
6
Size of buffer: 1000
File cpntents:
#p#
When I open file in notebook, actual content of file is:
#p# & P ÿÿÿÿ& ðýb µ# ú ~ù 3 ÿÿÿÿÿÿÿÿ1 þb B# 3   è# 3  =A
The input entered into file saved and expected output to console with file is read:
This code isn't working as expected.
Here is the correct working solution in GCC:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void save_to_binary_file(const char* file_name, const char* text_data)
{
FILE* file = fopen(file_name, "wb");
if(file == NULL)
printf("Failed to open file %s\n", file_name);
if(fwrite(text_data, sizeof(char), strlen(text_data) + 1, file) != (strlen(text_data) + 1))
puts("Failed to write all text data\n");
fclose(file);
}
char* load_binary_file_as_text(const char* file_name)
{
FILE* file = fopen(file_name, "rb");
if(file == NULL)
printf("Failed to open file %s\n", file_name);
fseek(file, 0, SEEK_END);
size_t file_size_in_bytes = ftell(file);
fseek(file, 0, SEEK_SET);
char* read_buffer = (char*)malloc(file_size_in_bytes);
if(fread(read_buffer, 1, file_size_in_bytes, file) != file_size_in_bytes)
puts("Failed to read all the bytes\n");
fclose(file);
return read_buffer;
}
int main()
{
save_to_binary_file("Data.data", "ABCD");
char* buffer = load_binary_file_as_text("Data.data");
printf("%s\n", buffer);
free(buffer);
return 0;
}
The problem was the '&' in the fwrite() call. Removed it and works as expected.

Connecting stdout to stdin of the same process in Linux

I'm writing an app that (ab)uses an APL engine, libapl.so. The library contains a mechanism to allow me to capture results, but some stuff it dumps to stdout and stderr. So my question is, is there way a to capture stuff written to stdout rather than having it go to a screen, get piped to another process, or some such? Is there a way, for example, to connect stdout to stdin of the same process? I've tinkered with pipe2(), dup(2), and various bits of weirdness in GTK+/Glib, but I haven't hit the right incantation yet.
Did some more poking--at least one solution seems to be to create a fifo, open() it twice, once for reading, one for writing, and dup2() the writing fd to the stdout fd. This results in writes to stdout going through the fifo pipe where it can be read by the application. (Thanks for some inspiration by someone named Hasturkun, almost 7 years ago.)
Here's a bit of demo code:
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
int
main (int ac, char *av[])
{
char tname[64];
sprintf (tname, "/tmp/testpipe%d", (int)getpid ());
int rc = mkfifo (tname, 0666);
if (rc != 0) {
perror ("Creating fifo");
return 1;
}
int temp_in_fd = open (tname, O_NONBLOCK | O_RDONLY);
if (temp_in_fd < 0) {
perror ("Opening new input");
return 1;
}
int temp_out_fd = open (tname, O_NONBLOCK | O_WRONLY);
if (temp_out_fd < 0) {
perror ("Opening new output");
return 1;
}
FILE *temp_in = fdopen (temp_in_fd, "r");
if (!temp_in) {
perror ("Creating new input FILE");
return 1;
}
FILE *temp_out = fdopen (temp_out_fd, "w");
if (!temp_out) {
perror ("Creating new input FILE");
return 1;
}
dup2 (fileno (temp_out), STDOUT_FILENO);
printf("Woot!");
fflush(stdout);
#define BFR_SIZE 64
char bfr[BFR_SIZE];
ssize_t sz = fread (bfr, 1, BFR_SIZE, temp_in);
fprintf (stderr, "got %d bytes: \"%s\"\n", (int)sz, bfr);
fclose (temp_out);
fclose (temp_in);
unlink (tname);
return 0;
}

getc() skips first value of text file (C)

I am trying to read a text file separated by semicolons such as
3;7;9;
4;7;23;
However, every time I call
while ((c = getc(fp))!= EOF)
putchar(c);
it skips the first value (3) and only outputs:
;7;9;
4;7;23;
Is there any way to get the first value?
Thank you
using C Program.*/
include
int main(){
//file nane
const char *fileName="sample.txt";
//file pointer
FILE *fp;
//to store read character
char ch;
//open file in read mode
fp=fopen(fileName,"r");
if(fp==NULL){
printf("Error in opening file.\n");
return -1;
}
printf("Content of file\n");
while((ch=getc(fp))!=EOF){
printf("%c",ch);
}
fclose(fp);
return 0;
}

Dicom to .PLY Conversion using VTK

I am trying to convert a DICOM file into PLY format using VTK to further convert it into .pcd (point cloud format). I have followed the example provided here.
However in the above example the code is supposed to change .vtu format into .ply format. I changed the code to convert the .dcm format into .ply format as shown below. The build succeeded and the exe file is working as well, however, it does not write the required output file. Can anyone please point out where did I go wrong??
#include <vtkSmartPointer.h>
#include <vtkPolyData.h>
#include <vtkDICOMImageReader.h>
#include <vtkXMLPolyDataReader.h>
#include <vtkPLYWriter.h>
int main(int argc, char *argv[])
{
if(argc < 3)
{
std::cerr << "Required arguments: input.vtp output.ply" << std::endl;
return EXIT_FAILURE;
}
std::string inputFileName = argv[1];
std::string outputFileName = argv[2];
// Read the DICOM file in the specified directory.
vtkSmartPointer<vtkDICOMImageReader> reader =
vtkSmartPointer<vtkDICOMImageReader>::New();
reader->SetFileName(inputFilename.c_str());
reader->Update();
vtkSmartPointer<vtkPLYWriter> writer = vtkSmartPointer<vtkPLYWriter>::New();
writer->SetFileName(outputFileName.c_str());
writer->SetInputConnection(reader->GetOutputPort());
writer->Update();
return EXIT_SUCCESS;
}
Below is an example of a simple contouring of a DICOM file and extraction of the largest connected area of polydata from the Marching Cubes filter then saved as a PLY format file. This should answer your question.
`
#include <vtkSmartPointer.h>
#include <vtkPolyData.h>
#include <vtkDICOMImageReader.h>
#include "vtkMarchingCubes.h"
#include "vtkPolyDataConnectivityFilter.h"
#include <vtkPLYWriter.h>
int main(int argc, char *argv[])
{
if(argc < 3)
{
std::cerr << "Required arguments: input.dcm output.ply" << std::endl;
return EXIT_FAILURE;
}
std::string inputFileName = argv[1];
std::string outputFileName = argv[2];
// Read the DICOM file in the specified directory.
vtkSmartPointer<vtkDICOMImageReader> reader =
vtkSmartPointer<vtkDICOMImageReader>::New();
reader->SetFileName(inputFilename.c_str());
reader->Update();
//arb. threshold for bone based on CT Hounsfield Units
float isoValue = 400.0
vtkSmartPointer<vtkMarchingCubes> surface = vtkSmartPointer<vtkMarchingCubes>::New();
surface->SetInputConnection(reader->GetOutputPort());
surface->ComputeNormalsOn();
surface->SetValue(0, isoValue);
surface->Update()
// To remain largest region
vtkSmartPointer<vtkPolyDataConnectivityFilter> confilter =
vtkSmartPointer<vtkPolyDataConnectivityFilter>::New();
confilter->SetInputConnection(surface->GetOutputPort());
confilter->SetExtractionModeToLargestRegion();
confilter->Update();
vtkSmartPointer<vtkPLYWriter> writer = vtkSmartPointer<vtkPLYWriter>::New();
writer->SetFileName(outputFileName.c_str());
writer->SetInputConnection(confilter->GetOutputPort());
writer->Update();
return EXIT_SUCCESS;
}

Assertion error with imshow

OK, i know this question may not be new and I've already gone through a few posts covering the same issue but it hasn't really helped. I am new to opencv and I am trying to load an image (in a folder that's different from the one where the executable file's stored) using imread and display it using imshow. Its the part of a much bigger code but I've shown the part that covers the issue as a separate code here:
#include <stdio.h>
#include "cv.h"
#include "cvaux.h"
#include "highgui.h"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/core.hpp"
#include <iostream>
#include "opencv2/contrib/contrib.hpp"
#include "opencv2/highgui/highgui_c.h"
#include "opencv/highgui.h"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#include "opencv2/legacy/legacy.hpp"
#include <fstream>
#include <sstream>
#include <cctype>
#include <iterator>
#include <cstring>
#include <highgui.h>
#include <string.h>
int disp(char * filename);
using namespace std;
using namespace cv;
int main()
{
disp("file.txt");
}
int disp(char * filename)
{
FILE * fp;
char shr[50];
char ch;
if( !(fp = fopen(filename, "rt")) )
{
fprintf(stderr, "Can\'t open file %s\n", filename);
return 0;
}
for(i=0;ch != '\n';i++)
{
ch = fgetc(imgListFile);
shr[i] = ch;
}
string str(shr);
Mat image=imread(str.c_str(),1);
namedWindow( "Display Image", CV_WINDOW_AUTOSIZE );
imshow( "Display Image",image);
cvWaitKey(0);
}
The "file.txt" is a text file containing the full path of the image i want to load and display. I am reading it into a character array, converting it to a string and passing it to the imshow/imread functions. I am not getting any errors while compiling, however, i am getting an error while i run the code:
OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow, file /home/ubuntu/Desktop/OpenCV/opencv-2.4.6.1/modules/highgui/src/window.cpp, line 261
terminate called after throwing an instance of 'cv::Exception'
what(): /home/ubuntu/Desktop/OpenCV/opencv-2.4.6.1/modules/highgui/src/window.cpp:261: error: (-215) size.width>0 && size.height>0 in function imshow
Aborted (core dumped)
I tried debugging the code, even re-compiled opencv; but i am getting the same issue again & again. I need help !!!
Hope i've explained my issue properly. Thanks in advance !!!
P.S: The text file actually contains a number before every image path; and i need to remove the number before i can feed the path to the imshow/imread functions; that's the reason i am trying to read the text file and store in a character array (so that i can get rid of the first 2 characters first).
The error message tells you that the image a 0 rows and/or 0 columns. This is usually caused by an incorrect path to image, or by an an image type that is not handled by your installation of OpenCV.
To debug it, you need to print out the argument of imread() and compare it with the catual location of the file on your system.
your for loop here is broken:
for(i=0;ch != '\n';i++)
{
ch = fgetc(imgListFile);
// you have to check the value of ch *after* reading
if ( ch == '\n' )
break; // else, you still append the '\n' to your filename
shr[i] = ch;
}
// z terminate
shr[i] = 0;
so, - you get empty images because of broken path.
There are some typos in your code. Also, it appears as if you haven't completely grasped the concepts of file handling and string allocations using c++; I would advise you to read up on those.. I have re-written your code as follows,
int main()
{
disp("file.txt");
return EXIT_SUCCESS;
}
void disp(char* filename)
{
ifstream myReadFile;
char shr[500];
myReadFile.open(filename);
if(myReadFile.is_open())
while(!myReadFile.eof())
myReadFile >> shr;
string str(shr);
Mat image=imread(str.c_str(),1);
namedWindow( "Display Image", CV_WINDOW_AUTOSIZE );
imshow( "Display Image",image);
cvWaitKey(0);
}
Hope this helps.

Resources